<?php

namespace App\Store\Controllers\Order;

use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Services\Message\WxaccountMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Member\SiteMemberLv;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderCommissionLog;
use App\Store\Models\Order\OrderSales;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use App\Store\Models\Order\OrderSalesRedflush;
use App\Store\Models\Order\OrderSalesSendGoods;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\Goods;
use App\Store\Services\Member\CommonMember;
use Illuminate\Support\Facades\DB;

use App\Store\Validate\Order\OrderSales as ValidateOrderOrderSales;
use App\Store\Validate\Order\OrderRecovery as ValidateOrderOrderRecovery;

use App\Store\Models\Sysset\Score as SyssetScore;
use App\Store\Models\Wxapp\WxappCoupon;
use App\Store\Services\Financial;
use App\Store\Services\Order\OrderSales as ServicesOrderOrderSales;
use App\Store\Services\Wxcoupon\Wxcoupon;
use Illuminate\Support\Facades\Log;

/**
 * 销售开单
 */
class OrderSalesController extends Controller
{

    /**
     * 开单
     */
    public function dopostorder(Request $request)
    {
        $req_data = $request->only([
            'mobile', 'real_name', 'mem_card_no', 'lunar_bdate', 'solar_bdate', 'points_current', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'mixed_payment', 'pay_money', 'print_temp_id', 'total_preference',
            'order_at', 'is_maker', 'round_down_money', 'balance_money', 'pointstobalance', 'issendpoints', 'remark', 'goodslist', 'sendgoodslist', 'recoverygoodslist', 'order_total_discount_percent', 'order_total_discount_moeny', 'coupon_id'
        ]);

        info('开单提交参数：', $req_data);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids <= 0) { //获取当前权限下的门店
            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        } else {
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $Validate = new ValidateOrderOrderSales();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $goodslist = is_array($req_data['goodslist']) ? $req_data['goodslist'] : (is_array(json_decode($req_data['goodslist'], true)) ? json_decode($req_data['goodslist'], true) : []);

        if (count($goodslist) <= 0) {
            return response()->json(['code' => '001', 'msg' => '销售商品信息不能为空']);
        }


        if (!empty($req_data['mixed_payment'])) {
            foreach ($req_data['mixed_payment'] as $money) {
                if ($req_data['pay_money'] > 0 && $money < 0) {
                    return response()->json(['code' => '001', 'msg' => '输入的金额有误']);
                }
                if ($req_data['pay_money'] < 0 && $money > 0) {
                    return response()->json(['code' => '001', 'msg' => '输入的金额有误']);
                }
            }
        }

        //校验订单商品信息
        $goodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checkgoods');
        $real_total_money_all = 0;
        $discount_money_all = 0;
        $total_money_all = 0;
        $goodscount = 0;
        $add_fee_total = 0;
        $order_points_total = 0;
        $share_mem_send_points = 0;
        $goods_moeny = ['su_money' => 0, 'notsu_money' => 0];
        foreach ($goodslist as $goods) {
            if (!$ValidateGoods->check($goods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }
            $goodsinfo = GoodsStockList::with(['storeinfo', 'startstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand', 'goods_content'])
                ->where(['cp_id' => $cp_id, 'id' => $goods['goods_stock_id'], 'store_id' => $current_store_id, 'is_del' => 1])->first();
            if (!$goodsinfo) {
                return response()->json(['code' => '001', 'msg' => '无效商品信息']);
            }
            $goodsinfo = $goodsinfo->toArray();

            if ($goodsinfo['count'] < $goods['count']) {
                return response()->json(['code' => '001', 'msg' => '商品库存不足']);
            }
            $price = 0;
            $real_total_money = 0;
            $costglod_price = 0;
            $label_price = 0;
            $old_recovery_price = 0;
            if ($goodsinfo['goods_category']['is_gram'] == 1) { //克算
                if ($goods['sales_price'] < 0) {
                    return response()->json(['code' => '001', 'msg' => '克重类商品销售金额不能小于0']);
                }
                $lastprice = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'goods_category_id' => $goodsinfo['goods_category']['id'], 'is_del' => 1])
                    ->where('date_str', '<=', date('Y-m-d'))
                    ->orderBy('date_str', 'desc')
                    ->first();
                if (!$lastprice) {
                    return response()->json(['code' => '001', 'msg' => $goodsinfo['goods_name'] . '暂未设置价格']);
                }

                if ($goods['sales_price'] < $lastprice['sales_limit_min_price']) {
                    return response()->json(['code' => '001', 'msg' => '克重类商品销售金额不能小于最低销售牌价']);
                }
                // $costglod_price = $lastprice->sales_price;
                $costglod_price = $goods['sales_price'];
                $old_recovery_price = $lastprice->back_company_price;
                $price = $costglod_price;
            } else {

                if ($goodsinfo['goods_category']['is_virtually'] == 1) {

                    // 判单是否有标签价，如果有则取标签价，如果么有则取分类维护的那个价格
                    if ($goodsinfo['label_price'] > 0) {
                        $price = $goods['label_price'] ?? 0;
                    } else {
                        // 销售金价价格等于sales_price
                        $price = $goods['sales_price'] ?? 0;
                    }


                } else {
                    // 折扣不为空时进行验证
                    if (isset($goods['discount']) && $goods['discount'] > 0 && $goods['discount'] < $goodsinfo['goods_category']['price_discount']) {
                        return response()->json(['code' => '001', 'msg' => '标价类商品折扣不能小于标价折扣']);
                    }

                    $label_price = $goodsinfo['label_price'];
                    $price = $label_price;
                }

            }
            $order_points = 0;
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'goods_stock_id' => $goods['goods_stock_id'],
                'is_gram' => $goodsinfo['goods_category']['is_gram'],
                'goodsinfo' => json_encode($goodsinfo),
                'weight' => $goodsinfo['goods_category']['is_gram'] == 1 ? floatval($goods['weight']) : ($goodsinfo['goods_category']['is_virtually'] == 1 ? floatval($goods['weight']) : $goodsinfo['piece_weight'] * $goods['count']),
                'costglod_price' => $costglod_price,
                'label_price' => $label_price,
                'price' => $price,
                'count' => $goods['count'],
                // 'total_money' => $price * $goods['count'],
                // 'real_total_money'=>$real_total_money,
                'cost_price' => isset($goods['cost_price']) ? intval($goods['cost_price']) : 0,
                'pieceprice_fee' => $goods['pieceprice_fee'],
                'cost_price_discount' => isset($goods['cost_price_discount']) ? intval($goods['cost_price_discount']) : 0,
                'discount' => isset($goods['discount']) ? bcdiv(bcmul($goods['discount'], 100, 0), 100, 2) : 0,
                'glod_price_discount' => isset($goods['glod_price_discount']) ? intval($goods['glod_price_discount']) : 0,
                'truncate_glod_weight' => (isset($goods['truncate_glod_weight']) && is_numeric($goods['truncate_glod_weight'])) ? $goods['truncate_glod_weight'] : 0,
                'truncate_glod_money' => isset($goods['truncate_glod_money']) ? intval($goods['truncate_glod_money']) : 0,
                'discount_money' => isset($goods['discount_money']) ? intval($goods['discount_money']) : 0,
                'add_fee1' => isset($goods['add_fee1']) ? intval($goods['add_fee1']) : 0,
                'add_fee2' => isset($goods['add_fee2']) ? intval($goods['add_fee2']) : 0,

                'gemstone_fee1' => isset($goods['gemstone_fee1']) ? intval($goods['gemstone_fee1']) : 0,
                'gemstone_fee2' => isset($goods['gemstone_fee2']) ? intval($goods['gemstone_fee2']) : 0,

                'remark' => isset($goods['remark']) ? $goods['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'order_points' => $order_points,
                'goods_name' => $goodsinfo['goods_name'],
                'goods_category_id' => $goodsinfo['goods_category_id'],
                'goods_sn_code' => $goodsinfo['goods_sn_code'],
                'main_stone_weigth' => $goodsinfo['main_stone_weigth'],
                'sales_price' => $costglod_price,
                'old_recovery_price' => $old_recovery_price,
                //统计需要记录
                'goods_brand_id' => $goodsinfo['goods_brand_id'],
                'goods_style_id' => $goodsinfo['goods_style_id'],
                'goods_cabinetgroup_id' => $goodsinfo['goods_category']['goods_cabinetgroup_id'],
                'is_sujin' => $goodsinfo['goods_category']['is_sujin'],
                'is_code_more' => $goods['is_code_more'],
                'money_received' => $goods['money_received'] ?? 0,
            ];


            $item['weight_old'] = isset($goods['weight_old']) ? floatval($goods['weight_old']) : $item['weight'];
            $item['label_price_old'] = isset($goods['label_price_old']) ? floatval($goods['label_price_old']) : $item['label_price'];
//            if ($goodsinfo['goods_category']['is_virtually'] == 1) {
//                $item['label_price'] = isset($goods['label_price']) ? floatval($goods['label_price']) : $item['label_price_old'];
//                $price = $item['label_price'];
//            }


            if ($item['is_gram'] == 1 && $goodsinfo['goods_category']['is_virtually'] != 1) {
                if ($goodsinfo['total_netglod_weight'] < $goods['weight']) {
                    return response()->json(['code' => '001', 'msg' => '库存总金重不足']);
                }

                //total_money =重量*（如果是虚拟则取标签价，如果是按克算，则取销售价）+重量*克销工费+重量*件销工费+附加费+宝石费
                $item['total_money'] = intval(bcmul($item['weight'], $price)) + intval(bcmul($item['weight'], $item['cost_price'])) + intval(bcmul($item['count'], $item['pieceprice_fee']))
                    + $item['add_fee1'] + $item['add_fee2'] + $item['gemstone_fee1'] + $item['gemstone_fee2'];


                $real_total_money = $item['total_money'] - intval(bcmul($item['weight'], $item['cost_price_discount'])) - intval(bcmul($item['weight'], $item['glod_price_discount'])) -
                    $item['truncate_glod_money'] - $item['discount_money'];

                // Log::info($item['total_money'].' - '.intval($item['weight'] * ($item['cost_price_discount'])).' -'.intval( $item['weight'] * $item['glod_price_discount']).' -'.
                // $item['truncate_glod_money'].' - '.$item['discount_money']);
                // Log::info($real_total_money);

                //  $goodsinfo['costglod_price']成本金价[输入] $goodsinfo['costgram_fee']  克算商品成本工费
                /**
                 *
                 *
                 *
                 * `gramprice_fee` int(10) NOT NULL DEFAULT '0' COMMENT '克销工费',
                 * `label_price` int(10) NOT NULL DEFAULT '0' COMMENT '标签价',
                 * `pieceprice_fee` int(10) NOT NULL DEFAULT '0' COMMENT '件销工费',
                 * `piece_weight` decimal(10,3) NOT NULL DEFAULT '0.000' COMMENT '件重(单位为g，保留三位小数)',
                 * `netglod_weight` decimal(10,3) NOT NULL DEFAULT '0.000' COMMENT '净金重',
                 * `content` varchar(32) NOT NULL DEFAULT '' COMMENT '含量',
                 * `costglod_price` int(10) NOT NULL DEFAULT '0' COMMENT '成本金价[输入]',
                 * `costpiece_fee` int(10) NOT NULL DEFAULT '0' COMMENT '件成本工费',
                 * `costgram_fee` int(10) NOT NULL DEFAULT '0' COMMENT '克成本工费',
                 * `piececost_fee` int(10) NOT NULL DEFAULT '0' COMMENT '单件成本',
                 */
                // 成本=(成本金价+克成本工费)*重量+数量*件成本工费
                //  $goodsinfo_total_cost = $goodsinfo['costglod_price'] + $goodsinfo['costgram_fee'];
                // $item['cost_fee'] = intval(bcmul($item['weight'], $goodsinfo_total_cost)) + intval(bcmul($item['count'], $goodsinfo['costpiece_fee']));
                // 成本=库存里的总成本/总金重*返厂总金重
                $item['cost_fee'] = ($goodsinfo['total_cost_fee'] / $goodsinfo['total_netglod_weight']) * $item['weight'];

            } else {

                if ($goodsinfo['goods_category']['is_virtually'] == 1) {
                    // 库存有标签价，那么就用标签价
                    if ($goodsinfo['label_price'] > 0) {
                        $item['total_money'] = $goods['count'] * $price;
                    } else {
                        // 销售金价价格等于sales_price
                        $item['total_money'] = $goods['count'] * $price * ($item['weight'] ?? 0);
                    }

                } else {
                    if ($goodsinfo['total_piece_weight'] < $item['weight']) {
                        return response()->json(['code' => '001', 'msg' => '库存总件重不足']);
                    }
                    $item['total_money'] = intval($goods['count'] * $price) + $item['add_fee1'] + $item['add_fee2'] + $item['gemstone_fee1'] + $item['gemstone_fee2'];
                }

                // $discounttomoney = 0;
                if ($item['discount'] > 0 && $item['discount'] < 100) {
                    $real_total_money = intval($item['total_money'] * $item['discount'] / 100);
                } else {
                    $real_total_money = $item['total_money'];
                }
                $real_total_money = $real_total_money - $item['discount_money'];
                // 成本=数量*单件成本
                $item['cost_fee'] = $goods['count'] * $goodsinfo['piececost_fee'];
            }


            if ($item['is_sujin'] == 1) {
                $goods_moeny['su_money'] += $real_total_money;
            } else {
                $goods_moeny['notsu_money'] += $real_total_money;
            }

            //order_points,计算积分

            $add_fee_total += ($item['add_fee1'] + $item['add_fee2']);
            $real_total_money = $real_total_money > 0 ? $real_total_money : 0;
            $item['real_total_money'] = $real_total_money;
            $item['real_total_money_without_mian'] = $real_total_money;
            $real_total_money_all += $real_total_money;
            $item['self_discount'] = ($item['total_money'] - $real_total_money);
            $discount_money_all += $item['self_discount'];
            $total_money_all += $item['total_money'];
            $goodscount += $item['count'];
            $order_points_total += $order_points;
            $goodslist_new[] = $item;
        }


//        Log::info('goodslist_new:'.json_encode($goodslist_new));
        //赠品
        $sendgoodslist = is_array($req_data['sendgoodslist']) ? $req_data['sendgoodslist'] : (is_array(json_decode($req_data['sendgoodslist'], true)) ? json_decode($req_data['sendgoodslist'], true) : []);
        //校验赠品信息
        $sendgoodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checksendgoods');
        foreach ($sendgoodslist as $sendgoods) {
            if (!$ValidateGoods->check($sendgoods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }
            $sendgoodsinfo = GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'id' => $sendgoods['send_goods_stock_id'], 'is_del' => 1])->first();
            if (!$sendgoodsinfo) {
                return response()->json(['code' => '001', 'msg' => '无效赠品信息']);
            }
            $sendgoodsinfo = $sendgoodsinfo->toArray();

            if ($sendgoodsinfo['count'] < $sendgoods['count']) {
                return response()->json(['code' => '001', 'msg' => '赠品库存不足']);
            }
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'send_goods_stock_id' => $sendgoods['send_goods_stock_id'],
                'count' => $sendgoods['count'],
                'send_goods_info' => json_encode($sendgoodsinfo),
                'goods_sn_code' => $sendgoodsinfo['goods_sn_code'],
                'sendgoods_name' => $sendgoodsinfo['sendgoods_name'],
                'pieceprice' => $sendgoodsinfo['pieceprice'],
                'create_at' => time(),
                'update_at' => time(),
            ];
            $sendgoodslist_new[] = $item;
        }

        //旧料
        $recoverygoodslist = is_array($req_data['recoverygoodslist']) ? $req_data['recoverygoodslist'] : (is_array(json_decode($req_data['recoverygoodslist'], true)) ? json_decode($req_data['recoverygoodslist'], true) : []);
        //校验旧料信息
        $recoverygoodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checkrecoverygoods');
        $total_recovery_money = 0;
        $dold_fee_total = 0;
        $order_points_recovery = 0;
        $valuations_total = 0;
        $recoverygoods_moeny = ['su_money' => 0, 'notsu_money' => 0];
        foreach ($recoverygoodslist as $recoverygoods) {
            if (!$ValidateGoods->check($recoverygoods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }

            if ($recoverygoods['recovery_type'] == 1) {
                $ValidateSub1 = new ValidateOrderOrderRecovery('subgoods1');
                if (!$ValidateSub1->check($recoverygoods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub1->getError()]);
                }

            }
            if ($recoverygoods['recovery_type'] == 2) {
                $ValidateSub2 = new ValidateOrderOrderRecovery('subgoods2');
                if (!$ValidateSub2->check($recoverygoods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub2->getError()]);
                }

            }
            $goods_brand_id = 0;
            if ($recoverygoods['change_type'] == 2) {
                if (!isset($recoverygoods['goods_sn_code']) || $recoverygoods['goods_sn_code'] == '') {
                    return response()->json(['code' => '001', 'msg' => '旧料上柜条码不能为空']);
                } else {
                    //查询商品库存是否存在此商品
                    //  $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'store_id' => $current_store_id,'is_del'=>1])->first();
                    $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                    if (empty($goodsStock)) {
                        return response()->json(['code' => '001', 'msg' => '不存在此商品无法上柜']);
                    }
                    $goods_brand_id = $goodsStock->goods_brand_id;
                    //
                }
            }

            $goods_categoryinfo = GoodsCategory::query()
                ->where('id', $recoverygoods['goods_category_id'])
                ->first();

            $lastprice = GoodsGlodprice::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'goods_category_id' => $recoverygoods['goods_category_id'], 'is_del' => 1])
                ->where('date_str', '<=', date('Y-m-d'))
                ->orderBy('date_str', 'desc')
                ->first();

            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'money' => abs($recoverygoods['money']),
                'change_type' => $recoverygoods['change_type'],
                'recovery_type' => $recoverygoods['recovery_type'],
                'goods_category_id' => $recoverygoods['goods_category_id'],
                'goods_catefory_name' => GoodsCategory::where(['cp_id' => $cp_id, 'id' => $recoverygoods['goods_category_id']])->value('category_name'),
                'goods_sn_code' => isset($recoverygoods['goods_sn_code']) ? $recoverygoods['goods_sn_code'] : '',
                'count' => $recoverygoods['count'],
                'weight' => isset($recoverygoods['weight']) ? doubleval($recoverygoods['weight']) : 0,
                'price' => isset($recoverygoods['price']) ? intval($recoverygoods['price']) : 0,
                'd_price' => isset($recoverygoods['d_price']) ? intval($recoverygoods['d_price']) : 0,
                'discount' => isset($recoverygoods['discount']) ? bcdiv(bcmul($recoverygoods['discount'], 100, 0), 100, 2) : 0,
                'dold_price' => isset($recoverygoods['dold_price']) ? intval($recoverygoods['dold_price']) : 0,
                'dold_fee' => isset($recoverygoods['dold_fee']) ? intval($recoverygoods['dold_fee']) : 0,
                'loss_weight' => isset($recoverygoods['loss_weight']) ? intval($recoverygoods['loss_weight']) : 0,
                'remark' => isset($recoverygoods['remark']) ? $recoverygoods['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'order_points' => 0,
                'sales_price' => $lastprice ? $lastprice->sales_price : 0,
                'old_recovery_price' => $lastprice ? $lastprice->back_company_price : 0,
                'goods_brand_id' => $goods_brand_id,
                'cost_fee' => ($recoverygoods['change_type'] == 2 && isset($isexist)) ? ($isexist['goods_category']['is_gram'] == 1 ? (($isexist['costglod_price'] + $isexist['costglod_price']) * $isexist['netglod_weight']) : $isexist['piececost_fee']) : 0,
                'is_sujin' => $goods_categoryinfo['is_sujin'],
                'sales_goods_id'=>$recoverygoods['sales_goods_id']??0
            ];


            if ($item['is_sujin'] == 1) {
                $recoverygoods_moeny['su_money'] += $recoverygoods['money'];
            } else {
                $recoverygoods_moeny['notsu_money'] += $recoverygoods['money'];
            }

            $item['valuations'] = ($item['old_recovery_price'] * $item['weight']);
            $recoverygoodslist_new[] = $item;
            $total_recovery_money += $item['money'];
            $dold_fee_total += $item['dold_fee'];
            $valuations_total += $item['valuations'];
        }


        if (isset($req_data['mobile']) && !empty($req_data['mobile'])) {
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

            if (!$meminfo) {
                $memdata = [
                    'cp_id' => $cp_id,
                    'store_id' => $current_store_id,
                    'mobile' => $req_data['mobile'] ?? '',
                    'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                    'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                    'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                    'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                    'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                    'points_total' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                    'create_at' => time(),
                    'update_at' => time(),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                ];
                $ins_mem_id = Member::create($memdata)->id;
                CommonMember::setMemInitPoints($request, $ins_mem_id);
                $req_data['balance_money'] = 0;
                $req_data['pointstobalance'] = 0;

            } else {
                if (isset($req_data['balance_money']) && $req_data['balance_money'] > 0) {
                    if ($req_data['balance_money'] > $meminfo->pre_money) {
                        return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
                    }
                } else {
                    $req_data['balance_money'] = 0;
                }

                if (isset($req_data['pointstobalance']) && $req_data['pointstobalance'] > 0) {
                    if ($req_data['pointstobalance'] > $meminfo->pointstobalance) {
                        return response()->json(['code' => '001', 'msg' => '积分金额不足，请修改后重新下单']);
                    }

                } else {
                    $req_data['pointstobalance'] = 0;
                }
            }
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();
        } else {
            $meminfo = json_decode(json_encode(['id' => 0, 'pre_money' => 0, 'pointstobalance' => 0]));
        }


        //主订单计算相关
        $maindata = [
            'cp_id' => $cp_id,
            'store_id' => $current_store_id,
            'mem_id' => $meminfo->id,
            'classesset_id' => isset($req_data['classesset_id']) ? intval($req_data['classesset_id']) : 0,
            'order_sn' => StoreCommon::createOrderSn(),
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => isset($req_data['shopping_account_id2']) ? intval($req_data['shopping_account_id2']) : 0,
            'goods_total_money' => $total_money_all,
            'total_money' => $total_money_all,
            'changegoods_money' => $total_recovery_money,
            'discount_moeny' => $req_data['total_preference'] ?? 0,
            'goods_real_money' => $real_total_money_all,
            'real_money' => $real_total_money_all,
            'balance_money' => intval($req_data['balance_money']),
            'pointstobalance' => intval($req_data['pointstobalance']),
            // 'pay_money' => $real_total_money_all - $req_data['balance_money']-$req_data['pointstobalance'],
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'order_at' => isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time(),
            'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
            'coupon_id' => isset($req_data['coupon_id']) ? intval($req_data['coupon_id']) : 0,
            'print_temp_id' => isset($req_data['print_temp_id']) ? intval($req_data['print_temp_id']) : 0,
            'add_fee_total' => $add_fee_total,
            'order_points' => $order_points_total,
            'dold_fee_total' => $dold_fee_total,
            'valuations_total' => $valuations_total,
            'share_mem_send_points' => $share_mem_send_points,
            'order_points_recovery' => $order_points_recovery,
            'truncate_glod_weight' => array_sum(array_column($goodslist_new, 'truncate_glod_weight')),
            'truncate_glod_money' => array_sum(array_column($goodslist_new, 'truncate_glod_money')),
        ];
        $maindata['order_at'] = $maindata['order_at'] > 0 ? $maindata['order_at'] : time();
        $maindata['pay_type_name'] = $maindata['pay_type_id'] == 0 ? '' : ($maindata['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $maindata['pay_type_id']])->value('paytype_name'));
        $maindata['create_account_id'] = $accountinfo['id'];
        $maindata['update_account_id'] = $accountinfo['id'];
        $maindata['create_account_real_name'] = $accountinfo['real_name'];
        $maindata['update_account_real_name'] = $accountinfo['real_name'];
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['remark'] = isset($req_data['remark']) ? $req_data['remark'] : '';
        $maindata['is_maker'] = (isset($req_data['is_maker']) && $req_data['is_maker'] == 2) ? 2 : 0;

        $real_total_money_all = $real_total_money_all + $dold_fee_total;//加折旧工费
        // 此处有减去旧料，如果旧料金额的绝对值大于商品金额那么结果就是负数
        $real_total_money_all = $real_total_money_all - ($maindata['changegoods_money'] ?? 0);


//        if ($maindata['changegoods_money'] > 0) {
//            if ($maindata['changegoods_money'] < $real_total_money_all) {
//                //需要减去旧料金额
//                $real_total_money_all = $real_total_money_all - $maindata['changegoods_money'];
//            } else {
//                return response()->json(['code' => '001', 'msg' => '换货金额大于订单金额']);
//            }
//        }

        $main_other_discount = 0;
        if (isset($req_data['order_total_discount_percent']) && is_numeric($req_data['order_total_discount_percent']) && number_format($req_data['order_total_discount_percent']) > 0 && number_format($req_data['order_total_discount_percent']) < 100) {
            $req_data['order_total_discount_percent'] = bcdiv(bcmul($req_data['order_total_discount_percent'], 100, 0), 100, 2);
            $real_total_money_all_mark = $real_total_money_all;

            $real_total_money_all = intval($real_total_money_all_mark * $req_data['order_total_discount_percent'] / 100);
            $main_other_discount += intval($real_total_money_all_mark - $real_total_money_all);
            $maindata['order_discount'] = $req_data['order_total_discount_percent'];
            $maindata['order_discount_money'] = intval($real_total_money_all_mark - $real_total_money_all);

        } else {
            $maindata['order_discount'] = 0;
            $maindata['order_discount_money'] = 0;
        }

        if (isset($req_data['order_total_discount_moeny']) && intval($req_data['order_total_discount_moeny']) > 0 && $maindata['coupon_id'] > 0) {
            return response()->json(['code' => '001', 'msg' => '优惠券不可与整单优惠同时使用']);
        }

        if (isset($req_data['order_total_discount_moeny']) && intval($req_data['order_total_discount_moeny']) > 0) {
            $real_total_money_all = $real_total_money_all - intval($req_data['order_total_discount_moeny']);
            $main_other_discount += intval($req_data['order_total_discount_moeny']);
            $maindata['order_total_discount_moeny'] = intval($req_data['order_total_discount_moeny']);
        } else {
            $maindata['order_total_discount_moeny'] = 0;
        }

        $coupon_money = 0;
        // 如果存在用户
        if ($maindata['coupon_id'] > 0 && $meminfo->id > 0) {
            $coupon_info = WxappCouponCodeList::query()
                ->where([['mem_id', $meminfo->id], ['cp_id', $cp_id], ['id', $maindata['coupon_id']], ['is_used', 1], ['available_end_time', '>=', time()], ['transaction_minimum', '<=', $real_total_money_all]])
                ->where(function ($q) use ($current_store_id) {
                    $q->where('store_ids', '')->orWhereRaw('FIND_IN_SET(?,store_ids)', [$current_store_id]);
                })->first();
            $coupon_info = empty($coupon_info) ? [] : $coupon_info->toArray();
            Log::info('用户领取的卡券', $coupon_info);
            if (empty($coupon_info)) {

                return response()->json(['code' => '001', 'msg' => '无效优惠券或已过期']);
            }

            // 有优惠券的情况处理
            if ($coupon_info['stock_type'] == 'NORMAL') {
                if ($real_total_money_all >= $coupon_info['discount_amount']) {
                    $real_total_money_all = $real_total_money_all - $coupon_info['discount_amount'];
                    $coupon_money = $coupon_info['discount_amount'];
                } else {
                    $coupon_money = $real_total_money_all;
                    $real_total_money_all = 0;
                }

            } else {
                $coupon_money = $real_total_money_all - intval($real_total_money_all * $coupon_info['discount_percent'] / 100);
                $real_total_money_all = intval($real_total_money_all * $coupon_info['discount_percent'] / 100);
            }

            $main_other_discount += $coupon_money;

        }

        $maindata['round_down_money'] = isset($req_data['round_down_money']) ? abs($req_data['round_down_money']) : 0;

        if ($real_total_money_all > 0) {
            $main_other_discount += $maindata['round_down_money'];
            $real_total_money_all = $real_total_money_all - $maindata['round_down_money'];
            // $maindata['discount_moeny'] = $maindata['total_money'] - $real_total_money_all;
        } else {

            // 如果付款金额小于0
            $main_other_discount += -$maindata['round_down_money'];
            $real_total_money_all = -(abs($real_total_money_all) - $maindata['round_down_money']);
//            if($maindata['total_money'] - abs($real_total_money_all)>0){
//                $maindata['discount_moeny'] = $maindata['total_money'] - abs($real_total_money_all);
//            }else{
//                $maindata['discount_moeny'] = 0;
//            }
        }


        $maindata['real_money'] = $real_total_money_all;
        $maindata['coupon_money'] = $coupon_money;

        if ($meminfo->id > 0) {
            $maindata['pay_money'] = $real_total_money_all - ($maindata['balance_money'] ?? 0) - ($maindata['pointstobalance'] ?? 0);
        } else {
            $maindata['pay_money'] = $real_total_money_all;
        }

        if (abs($maindata['pay_money']) != abs($req_data['pay_money'])) {
            return response()->json(['code' => '001', 'msg' => '计算金额不一致;' . '服务端计算：' . $maindata['pay_money'] . ';客户端计算：' . $req_data['pay_money']]);
        }


        DB::beginTransaction();
        try {

            $p_id = OrderSales::create($maindata)->id;

            $sub_real_total_moeny = array_sum(array_column($goodslist_new, 'real_total_money'));

            $sub_order_discount_money = 0;
            $sub_order_total_discount_moeny = 0;
            $sub_coupon_money = 0;
            $sub_recovery_goods_meony = 0;
            $sub_dold_fee = 0;
            $sub_valuations = 0;
            $sub_balance_money = 0;
            $sub_pointstobalance = 0;
            $ordercommissionlog = [];

            foreach ($goodslist_new as $gk => &$gval) {
                $gval['pid'] = $p_id;
                $gval['mem_id'] = $meminfo->id;
                $gval['shopping_account_id1'] = $maindata['shopping_account_id1'];
                $gval['shopping_account_id2'] = $maindata['shopping_account_id2'];
                $gval['classesset_id'] = $maindata['classesset_id'];
                $gval['pay_type_id'] = $maindata['pay_type_id'];
                $gval['order_at'] = $maindata['order_at'];
                //计算整单优惠拆分
                if ($main_other_discount >= 0) {

                    if ($gval['real_total_money'] > 0) {
                        if (($gk + 1) == count($goodslist_new)) {
                            $gval['sub_order_discount_money'] = $maindata['order_discount_money'] - $sub_order_discount_money;
                            $gval['sub_order_total_discount_moeny'] = $maindata['order_total_discount_moeny'] - $sub_order_total_discount_moeny;
                            $gval['sub_coupon_money'] = $coupon_money - $sub_coupon_money;
                            $gval['sub_recovery_goods_meony'] = $total_recovery_money - $sub_recovery_goods_meony;
                            $gval['sub_dold_fee'] = $dold_fee_total - $sub_dold_fee;
                            $gval['sub_valuations'] = $valuations_total - $sub_valuations;
                            $gval['sub_balance_money'] = $maindata['balance_money'] - $sub_balance_money;
                            $gval['sub_pointstobalance'] = $maindata['pointstobalance'] - $sub_pointstobalance;

                        } else {
                            $bili = $gval['real_total_money'] / $sub_real_total_moeny;
                            if ($maindata['order_discount_money'] > 0) {//折扣
                                $gval['sub_order_discount_money'] = intval($maindata['order_discount_money'] * $bili);
                                $sub_order_discount_money += $gval['sub_order_discount_money'];
                            } else {
                                $gval['sub_order_discount_money'] = 0;
                            }

                            if ($maindata['order_total_discount_moeny'] > 0) {//整单优惠
                                $gval['sub_order_total_discount_moeny'] = intval($maindata['order_total_discount_moeny'] * $bili);
                                $sub_order_total_discount_moeny += $gval['sub_order_total_discount_moeny'];
                            } else {
                                $gval['sub_order_total_discount_moeny'] = 0;
                            }

                            if ($coupon_money > 0) {//优惠券优惠
                                $gval['sub_coupon_money'] = intval($coupon_money * $bili);
                                $sub_coupon_money += $gval['sub_coupon_money'];
                            } else {
                                $gval['sub_coupon_money'] = 0;
                            }

                            if ($total_recovery_money > 0) {
                                $gval['sub_recovery_goods_meony'] = intval($total_recovery_money * $bili);
                                $sub_recovery_goods_meony += $gval['sub_recovery_goods_meony'];
                            } else {
                                $gval['sub_recovery_goods_meony'] = 0;
                            }

                            if ($dold_fee_total > 0) {
                                $gval['sub_dold_fee'] = intval($dold_fee_total * $bili);
                                $sub_dold_fee += $gval['sub_dold_fee'];
                            } else {
                                $gval['sub_dold_fee'] = 0;
                            }

                            if ($valuations_total > 0) {
                                $gval['sub_valuations'] = intval($valuations_total * $bili);
                                $sub_valuations += $gval['sub_valuations'];
                            } else {
                                $gval['sub_valuations'] = 0;
                            }

                            if ($maindata['balance_money'] > 0) {
                                $gval['sub_balance_money'] = intval($maindata['balance_money'] * $bili);
                                $sub_balance_money += $gval['sub_balance_money'];
                            } else {
                                $gval['sub_balance_money'] = 0;
                            }

                            if ($maindata['pointstobalance'] > 0) {
                                $gval['sub_pointstobalance'] = intval($maindata['pointstobalance'] * $bili);
                                $sub_pointstobalance += $gval['sub_pointstobalance'];
                            } else {
                                $gval['sub_pointstobalance'] = 0;
                            }
                        }

                    } else {
                        $gval['main_other_discount'] = 0;
                        $gval['sub_recovery_goods_meony'] = 0;
                        $gval['sub_dold_fee'] = 0;
                        $gval['sub_valuations'] = 0;
                    }

                    $gval['real_total_money_with_balance'] = $gval['real_total_money'] - ($gval['sub_balance_money'] ?? 0) - ($gval['sub_pointstobalance'] ?? 0);
                    $gval['main_other_discount'] = ($gval['sub_order_discount_money'] ?? 0) + ($gval['sub_order_total_discount_moeny'] ?? 0) + ($gval['sub_coupon_money'] ?? 0);
                    $gval['real_total_money'] = $gval['real_total_money_without_mian'] - ($gval['main_other_discount'] ?? 0) - ($gval['sub_recovery_goods_meony'] ?? 0) + ($gval['sub_dold_fee'] ?? 0);
                    // $gval['real_total_money'] = $gval['real_total_money_without_mian'] - ($gval['main_other_discount'] ?? 0) - 0 + ($gval['sub_dold_fee'] ?? 0);
                } else {
                    $gval['main_other_discount'] = 0;
                    $gval['sub_recovery_goods_meony'] = 0;
                    $gval['sub_dold_fee'] = 0;
                    $gval['sub_valuations'] = 0;
                }
                $gval['total_discount_money'] = $gval['main_other_discount'] + $gval['self_discount'];
                //  毛利=商品实付金额+旧料估值-商品的成本
                $gval['grossprofits'] = $gval['real_total_money'] + $gval['sub_valuations'] - $gval['cost_fee'];
                // -$gval['sub_recovery_goods_meony']+$gval['sub_dold_fee']//是否重复
                $gval['grossprofits_old'] = $gval['grossprofits'];

                $sysscoreinfo = SyssetScore::where([['goods_category_id', $gval['goods_category_id']], ['cp_id', $cp_id], ['store_id', $current_store_id], ['type', 3], ['is_del', 1], ['start_time', '<=', date('Y-m-d')], ['end_time', '>=', date('Y-m-d')]])
                    ->orderBy('id', 'desc')->first();
                $discount = isset($gval['discount']) ? bcdiv(bcmul($gval['discount'], 100, 0), 100, 2) : 0;
                //计算积分、SyssetScore
                if (!$sysscoreinfo || $sysscoreinfo->value <= 0) {
                    $sysscoreinfo = SyssetScore::where([['goods_category_id', $gval['goods_category_id']], ['cp_id', $cp_id], ['store_id', $current_store_id], ['type', 1], ['is_del', 1]])
                        ->orderBy('id', 'desc')->first();
                    if ($sysscoreinfo && $sysscoreinfo->value > 0) {
                        if ($goodsinfo['goods_category']['is_gram'] == 2) {
                            //1、积分规则：标价类要设置低于折扣不产生积分
                            //2、积分=实收乘积分值
                            if (($sysscoreinfo && $discount >= $sysscoreinfo->min_discount) || $discount <= 0) {
                                $order_points = round($gval['real_total_money'] * doubleval($sysscoreinfo->value) / 10000);
                                $share_mem_send_points += round($order_points * ($sysscoreinfo ? doubleval($sysscoreinfo->rate) : 0) / 100);
                            } else {
                                $order_points = 0;
                                $share_mem_send_points += 0;
                            }
                        } else {
                            $order_points = round($gval['real_total_money'] * doubleval($sysscoreinfo->value) / 10000);
                            $share_mem_send_points += round($order_points * ($sysscoreinfo ? doubleval($sysscoreinfo->rate) : 0) / 100);
                        }
                    } else {
                        $order_points = 0;
                        $share_mem_send_points += 0;
                    }

                    Log::info('sysscoreinfo:' . json_encode($sysscoreinfo));
                    Log::info('销售：' . 'order_point:' . $order_points);
                } else {
                    if ($goodsinfo['goods_category']['is_gram'] == 2) {
                        if (($discount > 0 && $sysscoreinfo && $discount < $sysscoreinfo->min_discount) || $discount <= 0) {
                            $order_points = round($gval['real_total_money'] * doubleval($sysscoreinfo->value) / 10000);
                            $share_mem_send_points += round($order_points * ($sysscoreinfo ? doubleval($sysscoreinfo->rate) : 0) / 100);
                        } else {
                            $order_points = 0;
                            $share_mem_send_points += 0;
                        }
                    } else {
                        $order_points = round($gval['real_total_money'] * doubleval($sysscoreinfo->value) / 10000);
                        $share_mem_send_points += round($order_points * ($sysscoreinfo ? doubleval($sysscoreinfo->rate) : 0) / 100);
                    }

                    Log::info('real_total_money:' . json_encode($gval['real_total_money']));
                    Log::info('sysscoreinfo:' . json_encode($sysscoreinfo));
                    Log::info('加倍：' . 'order_point:' . $order_points);
                    Log::info('推荐人：' . intval($order_points * doubleval($sysscoreinfo->rate) / 100));
                }

                $points = $order_points > 0 ? $order_points : 0;
                $gval['order_points'] = $points;
                $order_points_total += $points;
            }

            $pandc_res = [];
            Log::info('用户积分:' . $order_points_total);

            // 旧料积分产生规则 = 旧料里包含有素金，新品里包含有非素金  （旧料素金金额减去新品素金金额）
            if ($recoverygoods_moeny['su_money'] > 0 && $goods_moeny['notsu_money'] > 0) {
                $order_points_recovery = $recoverygoods_moeny['su_money'] - $goods_moeny['su_money'];
                $order_points_recovery = $order_points_recovery > 0 ? round($order_points_recovery / 100) : 0;
                OrderSales::query()->where(['id' => $p_id])->update(['order_points_recovery' => $order_points_recovery]);
            }

            if ($maindata['pay_money'] > 0) {
                Log::info('用户积分:' . $order_points);
                OrderSales::query()->where(['id' => $p_id])->update(['order_points' => $order_points_total, 'share_mem_send_points' => $share_mem_send_points]);
                $pandc_res = ServicesOrderOrderSales::computePerformanceAndCommission($goodslist_new, $recoverygoodslist_new, $goods_moeny, $recoverygoods_moeny);
                info('计算业绩&绩效结果', $pandc_res);
            }


            // 整单金额大于0的时候，计算业绩&绩效
            $goodslist_new = empty($pandc_res['goodslist_new'] ?? []) ? $goodslist_new : $pandc_res['goodslist_new'];
            $recoverygoodslist_new = empty($pandc_res['recoverygoodslist_new'] ?? []) ? $recoverygoodslist_new : $pandc_res['recoverygoodslist_new'];

            $goods_stockIds = array_column($goodslist_new, 'goods_stock_id');
            $stockList = (new GoodsStockList())->getGoodsStockByIds($cp_id, $goods_stockIds);

            foreach ($goodslist_new as $ggval) {
                //下单减少库存，如审核取消则库存退还，如修改订单则更改库存
                $stock = $stockList[$ggval['goods_stock_id']] ?? [];
                $stockInfo = $stock;
                if (empty($stock)) {
                    return response()->json(['code' => '001', 'msg' => '该商品' . $ggval['goods_stock_id'] . '不存在']);
                }

                $stock['count'] = $stock['count'] - $ggval['count'];
                $stock['sales_count'] = $stock['sales_count'] + $ggval['count'];

                if ($stock['count'] < 0) {
                    return response()->json(['code' => '001', 'msg' => '该商品' . $ggval['goods_stock_id'] . '数量不够扣减']);
                }


                if ($ggval['is_code_more'] == 2) {
                    $stock['total_netglod_weight'] = $stock['total_netglod_weight'] - $ggval['weight'];
                    $ggval['total_netglod_weight'] = $ggval['weight'];
                } else {
                    // 非一码多货 总件重和总金重
                    if ($stock['total_piece_weight'] > 0) {
                        $stock['total_piece_weight'] = $stock['total_piece_weight'] - ($stock['piece_weight'] * $ggval['count']);
                        $ggval['total_netglod_weight'] = $stock['piece_weight'] * $ggval['count'];
                    }
                    if ($stock['total_netglod_weight'] > 0) {
                        $stock['total_netglod_weight'] = $stock['total_netglod_weight'] - ($stock['netglod_weight'] * $ggval['count']);
                        $ggval['total_netglod_weight'] = $stock['netglod_weight'] * $ggval['count'];
                    }
                }
                list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($stockInfo, $ggval);
                // $total_cost_fee = (new Goods())->computeOriginalTotalCost($stock, $stock['is_gram']);
                $stockData = [
                    'count' => $stock['count'],
                    'sales_count' => $stock['sales_count'],
                    'total_piece_weight' => $stock['total_piece_weight'] ?? 0,
                    'total_netglod_weight' => $stock['total_netglod_weight'] ?? 0,
                    'total_cost_fee' => $remaining_cost_fee
                ];
                GoodsStockList::query()
                    ->where(['cp_id' => $cp_id, 'id' => $ggval['goods_stock_id'], 'store_id' => $current_store_id, 'is_del' => 1])
                    ->update($stockData);
                $goodsinfo = json_decode($ggval['goodsinfo'], true);
                $goodsinfo['total_cost_fee'] = $deduct_total_cost_fee;
                $goodsinfo['weight'] = $ggval['weight'];
                Goods::goodsLogSales($request, 0, intval($current_store_id), $goodsinfo, intval($ggval['count']), 91, $maindata['order_sn']);

                $ggval['total_cost_fee'] = $deduct_total_cost_fee;

                $sub_id = OrderSalesGoods::query()->create($ggval)->id;


                if ($ggval['is_gram'] == 1) {
                    $ordercommissionlog[] = [
                        'cp_id' => $cp_id,
                        'store_id' => $ggval['store_id'],
                        'pid' => $p_id,
                        'sub_id' => $sub_id,
                        'type' => 2,
                        'commission1' => $ggval['commission1_price_d'] ?? 0,
                        'commission2' => $ggval['commission2_price_d'] ?? 0,
                        'order_at' => $maindata['order_at'],
                        'create_at' => $maindata['create_at'],
                        'classesset_id' => $maindata['classesset_id'],
                        'goods_style_id' => $ggval['goods_style_id'],
                        'order_sn' => $maindata['order_sn'],
                        'shopping_account_id1' => $maindata['shopping_account_id1'],
                        'shopping_account_id2' => $maindata['shopping_account_id2'],
                    ];

                    $ordercommissionlog[] = [
                        'cp_id' => $cp_id,
                        'store_id' => $ggval['store_id'],
                        'pid' => $p_id,
                        'sub_id' => $sub_id,
                        'type' => 3,
                        'commission1' => $ggval['commission1_cost_price_d'] ?? 0,
                        'commission2' => $ggval['commission2_cost_price_d'] ?? 0,
                        'order_at' => $maindata['order_at'],
                        'create_at' => $maindata['create_at'],
                        'classesset_id' => $maindata['classesset_id'],
                        'goods_style_id' => $ggval['goods_style_id'],
                        'order_sn' => $maindata['order_sn'],
                        'shopping_account_id1' => $maindata['shopping_account_id1'],
                        'shopping_account_id2' => $maindata['shopping_account_id2'],
                    ];

                    $ordercommissionlog[] = [
                        'cp_id' => $cp_id,
                        'store_id' => $ggval['store_id'],
                        'pid' => $p_id,
                        'sub_id' => $sub_id,
                        'type' => 4,
                        'commission1' => $ggval['commission1_cost_price'] ?? 0,
                        'commission2' => $ggval['commission2_cost_price'] ?? 0,
                        'order_at' => $maindata['order_at'],
                        'create_at' => $maindata['create_at'],
                        'classesset_id' => $maindata['classesset_id'],
                        'goods_style_id' => $ggval['goods_style_id'],
                        'order_sn' => $maindata['order_sn'],
                        'shopping_account_id1' => $maindata['shopping_account_id1'],
                        'shopping_account_id2' => $maindata['shopping_account_id2'],
                    ];
                } else {
                    $ordercommissionlog[] = [
                        'cp_id' => $cp_id,
                        'store_id' => $ggval['store_id'],
                        'pid' => $p_id,
                        'sub_id' => $sub_id,
                        'type' => 1,
                        'commission1' => $ggval['commission1_total'] ?? 0,
                        'commission2' => $ggval['commission2_total'] ?? 0,
                        'order_at' => $maindata['order_at'],
                        'create_at' => $maindata['create_at'],
                        'classesset_id' => $maindata['classesset_id'],
                        'goods_style_id' => $ggval['goods_style_id'],
                        'order_sn' => $maindata['order_sn'],
                        'shopping_account_id1' => $maindata['shopping_account_id1'],
                        'shopping_account_id2' => $maindata['shopping_account_id2'],
                    ];
                }
            }

            foreach ($sendgoodslist_new as &$sgval) {
                $sgval['pid'] = $p_id;
                $sgval['mem_id'] = $meminfo->id;
                $sgval['order_at'] = $maindata['order_at'];
                //更新库存相关
                //下单减少库存，如审核取消则库存退还，如修改订单则更改库存
                GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'id' => $sgval['send_goods_stock_id'], 'is_del' => 1])
                    ->decrement('count', $sgval['count']);
                $send_goods_info = json_decode($sgval['send_goods_info'], true);
                GoodsSendgoodsLog::create(
                    [
                        'cp_id' => $cp_id,
                        'store_id' => $current_store_id,
                        'target_store_id' => $current_store_id,
                        'type' => 2,
                        'sn_code' => $maindata['order_sn'],
                        'sendgoods_name' => $send_goods_info['sendgoods_name'],
                        'goods_sn_code' => $send_goods_info['goods_sn_code'],
                        'count' => $sgval['count'],
                        'pieceprice' => $send_goods_info['pieceprice'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '销售赠送'
                    ]
                );
            }


            $sujin = [];
            foreach ($recoverygoodslist_new as &$rgval) {
                $rgval['pid'] = $p_id;
                $rgval['mem_id'] = $meminfo->id;
                $rgval['order_at'] = $maindata['order_at'];
                $rgval['classesset_id'] = $maindata['classesset_id'];
                $rgval['shopping_account_id1'] = $maindata['shopping_account_id1'];
                $rgval['shopping_account_id2'] = $maindata['shopping_account_id2'];
                // 此处旧料更新积分，把旧料积分更新到第一个素金的商品上
                if (!in_array($item['is_sujin'], $sujin)) {
                    $sujin[] = $item['is_sujin'];
                    $rgval['order_points'] = $order_points_recovery;
                } else {
                    $rgval['order_points'] = 0;
                }

                // 上柜
                if ($rgval['change_type'] == 2) {

                    $salesrecoverygoods = OrderSalesRecoveryGoods::query()
                        ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $rgval['goods_sn_code'], 'change_type' => 2])
                        ->where('audit_status', '<>', 3)
                        ->selectRaw('sum(count) as total')
                        ->first();
                    $salesrecoverygoods = empty($salesrecoverygoods) ? [] : $salesrecoverygoods->toArray();


                    $recoverygoods = OrderRecoveryGoods::query()
                        ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $rgval['goods_sn_code'], 'change_type' => 2])
                        ->where('audit_status', '<>', 3)
                        ->selectRaw('sum(count) as total')
                        ->first();
                    $recoverygoods = empty($recoverygoods) ? [] : $recoverygoods->toArray();

                    $count = $rgval['count'] + ($recoverygoods['total'] ?? 0) + ($salesrecoverygoods['total'] ?? 0);
                    $orderSales = OrderSalesGoods::query()
                        ->where(['cp_id' => $cp_id, 'is_del' => 1, 'goods_sn_code' => $rgval['goods_sn_code'], 'red_status' => 1])
                        ->where('audit_status', '<>', 3)
                        ->selectRaw('sum(count) as total')
                        ->first();

                    if (empty($orderSales)) {
                        return response()->json(['code' => '001', 'msg' => '本厂不存在此商品无法上柜']);
                    }
                    $orderSales['total'];
                    if ((int)$count > (int)$orderSales['total']) {
                        return response()->json(['code' => '001', 'msg' => '上柜的商品数量不能大于本厂的商品数量']);
                    }

                    $sales_goods_id = $rgval['sales_goods_id'] ?? 0;
                    if ($sales_goods_id > 0) {
                        $saleGoodsInfo = OrderSalesGoods::query()->where('id', $sales_goods_id)->first();
                        if(empty($saleGoodsInfo)){
                            return response()->json(['code' => '001', 'msg' => '上柜的商品不存在']);
                        }
                        $saleGoodsInfo = empty($saleGoodsInfo) ? [] : $saleGoodsInfo->toArray();
                        $goodsinfo = json_decode($saleGoodsInfo['goodsinfo'], true);
                        $saleGoodsInfo['goodsinfo'] = $goodsinfo;
                        $saleGoodsInfo['goods_style_id'] = $saleGoodsInfo['goodsinfo']['goods_style_id'] ?? 0;
                        $saleGoodsInfo['is_code_more'] = $saleGoodsInfo['goodsinfo']['is_code_more'] ?? 0;

                        $rgval['sales_goods_id'] = $sales_goods_id;
                        $rgval['is_code_more'] = $saleGoodsInfo['is_code_more'] ?? 0;
                        $rgval['goods_style_id'] = $saleGoodsInfo['goods_style_id'] ?? 0;
                        $rgval['total_money'] = $sales_goods_id > 0 ? intval(bcmul(bcdiv($saleGoodsInfo['real_total_money'], $saleGoodsInfo['count'], 2), $rgval['count'])) : 0;
                        $rgval['sales_goods_performance'] = $saleGoodsInfo['performance'] ?? 0;

                    }else{
                        return response()->json(['code' => '001', 'msg' => '上柜的商品不存在']);
                    }
                }

                // 此处需要取卖的出去的订单商品最后一条数据的总成本
                $recovery_total_netglod_weight = 0;
                if (!empty($rgval['goods_sn_code'])) {
                    $salesGoods = OrderSalesGoods::query()
                        ->where('cp_id', $cp_id)
                        ->where('is_del', 1)
                        ->where('goods_sn_code', $rgval['goods_sn_code'])
                        ->orderBy('id', 'desc')
                        ->first();

                    $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
                    $goodsinfo = empty($salesGoods) ? [] : (array)(json_decode($salesGoods['goodsinfo']));
                    if (!empty($goodsinfo)) {
                        if ($goodsinfo['is_code_more'] == 2) {
                            $recovery_total_netglod_weight = $rgval['weight'];
                        } else {
                            $recovery_total_netglod_weight = $goodsinfo['netglod_weight'] * $rgval['count'];
                        }

                    }

                }
                // $weight =$rgval['weight']-(!empty($rgval['loss_weight'])?$rgval['loss_weight']:0);
                list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsinfo, ['total_netglod_weight' => $recovery_total_netglod_weight]);
                $rgval['total_cost_fee'] = $deduct_total_cost_fee;

                $sub_id = OrderSalesRecoveryGoods::create($rgval)->id;

                $ordercommissionlog[] = [
                    'cp_id' => $cp_id,
                    'store_id' => $rgval['store_id'],
                    'pid' => $p_id,
                    'sub_id' => $sub_id,
                    'type' => 5,
                    'commission1' => $rgval['commission1'] ?? 0,
                    'commission2' => $rgval['commission2'] ?? 0,
                    'order_at' => $maindata['order_at'],
                    'create_at' => $maindata['create_at'],
                    'classesset_id' => $maindata['classesset_id'],
                    'goods_style_id' => 0,
                    'order_sn' => $maindata['order_sn'],
                    'shopping_account_id1' => $maindata['shopping_account_id1'],
                    'shopping_account_id2' => $maindata['shopping_account_id2'],
                ];

            }
            count($sendgoodslist_new) > 0 && OrderSalesSendGoods::insert($sendgoodslist_new);
            // count($recoverygoodslist_new) > 0 && OrderSalesRecoveryGoods::insert($recoverygoodslist_new);

            OrderCommissionLog::insert($ordercommissionlog);

            if ($maindata['coupon_id'] > 0) {//设置优惠券已使用
                WxappCouponCodeList::where(['id' => $maindata['coupon_id']])->update(['is_used' => 2, 'used_at' => time(), 'user_order_id' => $p_id]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('创建订单失败' . $e->getFile() . $e->getLine() . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '创建订单失败']);
        }

        $printdata = $request->is_print == 1 ? ServicesOrderOrderSales::getOrderPrintData($p_id, $request) : [];
        $info = OrderSales::where(['id' => $p_id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!empty($info)) {
            // 给用户发送消息
            $info->mem_id > 0 && WxaccountMessage::sendwx($cp_id, $info->mem_id, 'sales_order', $info->toArray());
            //给店长发送消息
            WxaccountMessage::sendwxinner($cp_id, $info->store_id, 'sales_order', $info->toArray());
        }

        return response()->json(['code' => '000', 'msg' => '创建订单成功', 'data' => $printdata]);
    }

    /**
     * 挂单支付
     */
    public function doordermakerpay(Request $request)
    {
        $req_data = $request->only([
            'id', 'classesset_id', 'pay_type_id', 'mixed_payment', 'print_temp_id', 'order_at', 'issendpoints',
        ]);

        $id = $req_data['id'] ?? 0;

        if (!isset($req_data['pay_type_id']) || empty($req_data['pay_type_id'])) {
            return response()->json(['code' => '001', 'msg' => '请选择支付方式']);
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        if ($info->is_maker != 2) {
            return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        }
        $updata = [
            'classesset_id' => isset($req_data['classesset_id']) ? intval($req_data['classesset_id']) : 0,
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'pay_type_name' => empty($req_data['pay_type_id']) ? '' : ($req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name')),
            'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
            'order_at' => isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time(),
            'is_maker' => 1,
            'update_at' => time()
        ];
        OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
            ->update($updata);
        $printdata = $request->is_print == 1 ? ServicesOrderOrderSales::getOrderPrintData($id, $request) : [];
        return response()->json(['code' => '000', 'msg' => '订单支付成功', 'data' => $printdata]);

    }

    /**
     * 挂单支付批量
     */
    public function doordermakerpaymore(Request $request)
    {
        $req_data = $request->only([
            'ids', 'classesset_id', 'pay_type_id', 'mixed_payment', 'print_temp_id', 'order_at', 'issendpoints',
        ]);

        if (!isset($req_data['pay_type_id']) || empty($req_data['pay_type_id'])) {
            return response()->json(['code' => '001', 'msg' => '请选择支付方式']);
        }

        $ids = $req_data['ids'];
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $infolist = OrderSales::where(['cp_id' => $cp_id, 'is_del' => 1, 'is_maker' => 2])->whereIn('id', $ids)->get()->toArray();
        if (count($infolist) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        foreach ($infolist as $info) {
            $updata = [
                'classesset_id' => $req_data['classesset_id'],
                'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
                'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
                'pay_type_name' => empty($req_data['pay_type_id']) ? '' : ($req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name')),
                'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
                'order_at' => isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time(),
                'is_maker' => 1,
                'update_at' => time()
            ];
            OrderSales::where(['id' => $info['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                ->update($updata);
        }
        return response()->json(['code' => '000', 'msg' => '订单支付成功']);

    }

    /**
     * 挂单取消
     */
    public function doordermakercancel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        if ($info->is_maker != 2) {
            return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        }

        $goodslist = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();

        $sendgoodslist = OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();


        DB::beginTransaction();
        try {
            $goods_stock_ids = array_column($goodslist, 'goods_stock_id');
            $stockList = (new GoodsStockList())->getGoodsStockByIds($cp_id, $goods_stock_ids);
            foreach ($goodslist as $val) {
                $goods = $stockList[$val['goods_stock_id']] ?? [];
                $stock = $goods;
                $goods['count'] = $goods['count'] + $val['count'];
                $goods['sales_count'] = $goods['sales_count'] - $val['count'];
                if ($goods['is_code_more'] == 2) {
                    $goods['total_netglod_weight'] = $goods['total_netglod_weight'] + $val['weight'];
                    $val['total_netglod_weight'] = $val['weight'];
                } else {
                    // 非一码多货 总件重和总金重
                    if ($goods['total_piece_weight'] > 0) {
                        $goods['total_piece_weight'] = $goods['total_piece_weight'] + ($goods['piece_weight'] * $val['count']);
                        $val['total_piece_weight'] = $goods['piece_weight'] * $val['count'];
                    }
                    if ($goods['total_netglod_weight'] > 0) {
                        $goods['total_netglod_weight'] = $goods['total_netglod_weight'] + ($goods['netglod_weight'] * $val['count']);
                        $val['total_netglod_weight'] = $goods['netglod_weight'] * $val['count'];
                    }

                }
                list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stock, $val, $goods['is_gram']);

                // $total_cost_fee = (new Goods())->computeOriginalTotalCost($goods, $goods['is_gram']);
                $stockData = [
                    'count' => DB::raw('count +' . $val['count']),
                    'sales_count' => DB::raw('sales_count -' . $val['count']),
                    'total_piece_weight' => $goods['total_piece_weight'] ?? 0,
                    'total_netglod_weight' => $goods['total_netglod_weight'] ?? 0,
                    'total_cost_fee' => $total_cost_fee,
                    'costglod_price' => $costglod_price,
                    'piececost_fee' => $piececost_fee
                ];

                GoodsStockList::query()
                    ->where(['cp_id' => $cp_id, 'id' => $val['goods_stock_id'], 'store_id' => $val['store_id']])
                    ->update($stockData);

                $goodsinfo = json_decode($val['goodsinfo'], true);
                $goodsinfo['weight'] = $val['weight'];
                $goodsinfo['total_cost_fee'] = $val['total_cost_fee'];
                $goodsinfo['costglod_price'] = $costglod_price;
                $goodsinfo['piececost_fee'] = $piececost_fee;

                Goods::goodsLogSales($request, 0, intval($val['store_id']), $goodsinfo, intval($val['count']), 92, $info->order_sn);

            }
            foreach ($sendgoodslist as $val) {
                GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'id' => $val['send_goods_stock_id'], 'is_del' => 1])
                    ->increment('count', $val['count']);
                $send_goods_info = json_decode($val['send_goods_info'], true);
                GoodsSendgoodsLog::create(
                    [
                        'cp_id' => $cp_id,
                        'store_id' => $val['store_id'],
                        'target_store_id' => $val['store_id'],
                        'type' => 7,
                        'sn_code' => $info->order_sn,
                        'sendgoods_name' => $send_goods_info['sendgoods_name'],
                        'goods_sn_code' => $send_goods_info['goods_sn_code'],
                        'count' => $val['count'],
                        'pieceprice' => $send_goods_info['pieceprice'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '销售取消'
                    ]
                );
            }

            OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_maker' => 9, 'is_del' => 2, 'del_at' => time(), 'update_at' => time()]);
            OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->update(['is_del' => 2, 'del_at' => time()]);


            if ($info->coupon_id > 0) {//设置优惠券取消
                WxappCouponCodeList::where(['id' => $info->coupon_id])->update(['is_used' => 1, 'used_at' => 0, 'user_order_id' => 0]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '订单取消失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '挂单取消成功']);

    }

    /**
     * 订单列表
     */

    public function getorderlist(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
            $request->training_min = $training['training_min'];
            $request->training_max = $training['training_max'];
        }
        $list = OrderSales::getList($request);

        foreach ($list['list'] as &$val) {
            $val['total_grossprofits'] = array_sum(array_column($val['goodslist'], 'grossprofits'));
            $val['order_points'] = $val['order_points'] + $val['order_points_recovery'];
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSales::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist', 'recoverygoodslist', 'sendgoodslist', 'classessetinfo'])
            ->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $info = $info->toArray();

        if (isset($info['recoverygoodslist']) && !empty($info['recoverygoodslist'])) {
            foreach ($info['recoverygoodslist'] as &$recovery) {
                $recovery['money'] = -$recovery['money'];
            }
        }

        $goodslist = $info['goodslist'] ?? [];
        if (!empty($goodslist)) {
            foreach ($goodslist as &$item) {
                $goodsinfo = empty($item['goodsinfo']) ? [] : json_decode($item['goodsinfo'], true);
//                //商品工费单件=商品的克销工费+商品的件销工费
//                //商品工费 =克销工费*重量+件销工费*数量
//                $item['goods_costs_price'] = bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0);
//                $item['goods_costs_price_total'] = bcadd(($goodsinfo['gramprice_fee'] ?? 0) * ($item['weight'] ?? 0), ($goodsinfo['pieceprice_fee'] ?? 0) * ($item['count'] ?? 0), 2);
//
//                //销售工费单件=商品的克销工费+商品的件销工费-工费优惠填的值
//                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
//                $item['sale_costs_price'] = bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0) - ($item['cost_price_discount'] ?? 0);
//                $item['sale_costs_price_total'] = $item['goods_costs_price_total'] - ($item['cost_price_discount'] ?? 0) * ($item['weight'] ?? 0);


//               2025-10-16 再次修改公式调整
                //商品工费单价（字段应该是：商品克销工费）=商品的克销工费
                //商品工费 =克销工费*重量+件销工费
                $item['goods_costs_price'] = $goodsinfo['gramprice_fee'] ?? 0;
                $item['goods_costs_price_total'] = bcadd(($goodsinfo['gramprice_fee'] ?? 0) * ($item['weight'] ?? 0), ($goodsinfo['pieceprice_fee'] ?? 0), 2);

                //销售工费单价（字段应该是：销售克销工费）=商品的克销工费-工费优惠填的值
                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
                $item['sale_costs_price'] = ($goodsinfo['gramprice_fee'] ?? 0) - ($item['cost_price_discount'] ?? 0);
                $item['sale_costs_price_total'] = $item['goods_costs_price_total'] - ($item['cost_price_discount'] ?? 0) * ($item['weight'] ?? 0);
            }
        }
        $info['goodslist'] = $goodslist;


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }


    public function getinfobyordersn(Request $request)
    {
        $order_sn = $request->order_sn ?? '';
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSales::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist', 'recoverygoodslist', 'sendgoodslist', 'classessetinfo'])
            ->where(['order_sn' => $order_sn, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $info = $info->toArray();
        if (isset($info['recoverygoodslist']) && !empty($info['recoverygoodslist'])) {
            foreach ($info['recoverygoodslist'] as &$recovery) {
                $recovery['money'] = -$recovery['money'];
            }
        }

        $goodslist = $info['goodslist'] ?? [];
        if (!empty($goodslist)) {
            foreach ($goodslist as &$item) {
                $goodsinfo = empty($item['goodsinfo']) ? [] : json_decode($item['goodsinfo'], true);
                //商品工费单件=商品的克销工费+商品的件销工费
                //商品工费 =克销工费*重量+件销工费*数量
                $item['goods_costs_price'] = (float)bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0);
                $item['goods_costs_price_total'] = (float)bcadd(($goodsinfo['gramprice_fee'] ?? 0) * ($item['weight'] ?? 0), ($goodsinfo['pieceprice_fee'] ?? 0) * ($item['count'] ?? 0), 2);

                //销售工费单件=商品的克销工费+商品的件销工费-工费优惠填的值
                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
                $item['sale_costs_price'] = bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0) - ($item['cost_price_discount'] ?? 0);
                $item['sale_costs_price_total'] = $item['goods_costs_price_total'] - ($item['cost_price_discount'] ?? 0) * ($item['weight'] ?? 0);
            }
        }
        $info['goodslist'] = $goodslist;

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 订单编辑不能编辑商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function doorderedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'mixed_payment',
            'order_at', 'is_maker', 'round_down_money', 'balance_money', 'pointstobalance', 'issendpoints', 'remark', 'goodslist', 'sendgoodslist', 'recoverygoodslist', 'order_total_discount_percent', 'order_total_discount_moeny', 'coupon_id'
        ]);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];

        $info = OrderSales::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if (is_array($store_ids) || $store_ids == '' || $store_ids <= 0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        } else {
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }

        $Validate = new ValidateOrderOrderSales('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $goodslist = is_array($req_data['goodslist']) ? $req_data['goodslist'] : (is_array(json_decode($req_data['goodslist'], true)) ? json_decode($req_data['goodslist'], true) : []);

        if (count($goodslist) <= 0) {
            return response()->json(['code' => '001', 'msg' => '销售商品信息不能为空']);
        }
        //校验订单商品信息
        // $goodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checkgoods');
        $real_total_money_all = 0;
        $discount_money_all = 0;
        $total_money_all = 0;
        $goodscount = 0;
        foreach ($goodslist as $goods) {
            if (!$ValidateGoods->check($goods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }
            $goodsinfo = GoodsStockList::with(['storeinfo', 'startstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])
                ->where(['cp_id' => $cp_id, 'id' => $goods['goods_stock_id'], 'store_id' => $current_store_id, 'is_del' => 1])->first();
            if (!$goodsinfo) {
                return response()->json(['code' => '001', 'msg' => '无效商品信息']);
            }
            $goodsinfo = $goodsinfo->toArray();

            if ($goodsinfo['count'] < $goods['count']) {
                return response()->json(['code' => '001', 'msg' => '商品库存不足']);
            }
            $price = 0;
            $real_total_money = 0;
            $costglod_price = 0;
            $label_price = 0;
            if ($goodsinfo['goods_category']['is_gram'] == 1) { //克算
                $lastprice = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'goods_category_id' => $goodsinfo['goods_category']['id'], 'is_del' => 1])
                    ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();
                if (!$lastprice) {
                    return response()->json(['code' => '001', 'msg' => $goodsinfo['goods_name'] . '暂未设置价格']);
                }
                $costglod_price = $lastprice['sales_price'];
                $price = $costglod_price * $goodsinfo['netglod_weight'];
            } else {
                $label_price = $goodsinfo['label_price'];
                $price = $label_price;
            }


            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'goods_stock_id' => $goods['goods_stock_id'],
                'is_gram' => $goodsinfo['goods_category']['is_gram'],
                'goodsinfo' => json_encode($goodsinfo),
                'weight' => $goodsinfo['goods_category']['is_gram'] == 1 ? $goodsinfo['netglod_weight'] : $goodsinfo['piece_weight'],
                'costglod_price' => $costglod_price,
                'label_price' => $label_price,
                'price' => $price,
                'count' => $goods['count'],
                'total_money' => $price * $goods['count'],
                // 'real_total_money'=>$real_total_money,
                'cost_price' => isset($goods['cost_price']) ? intval($goods['cost_price']) : 0,
                'cost_price_discount' => isset($goods['cost_price_discount']) ? intval($goods['cost_price_discount']) : 0,
                'discount' => isset($goods['discount']) ? intval($goods['discount']) : 0,
                'glod_price_discount' => isset($goods['glod_price_discount']) ? intval($goods['glod_price_discount']) : 0,
                'truncate_glod_weight' => (isset($goods['truncate_glod_weight']) && is_numeric($goods['truncate_glod_weight'])) ? $goods['truncate_glod_weight'] : 0,
                'truncate_glod_money' => isset($goods['truncate_glod_money']) ? intval($goods['truncate_glod_money']) : 0,
                'discount_money' => isset($goods['discount_money']) ? intval($goods['discount_money']) : 0,
                'add_fee1' => isset($goods['add_fee1']) ? intval($goods['add_fee1']) : 0,
                'add_fee2' => isset($goods['add_fee2']) ? intval($goods['add_fee2']) : 0,
                'remark' => isset($goods['remark']) ? $goods['remark'] : '',
            ];

            if ($item['is_gram'] == 1) {
                $real_total_money = $item['total_money'] + intval($item['weight'] * $item['count'] * ($item['cost_price'] - $item['cost_price_discount'] - $item['glod_price_discount'])) -
                    ($item['truncate_glod_money']) - $item['discount_money'] + $item['add_fee1'] + $item['add_fee2'];
            } else {
                $discounttomoney = 0;
                if ($item['discount'] > 0 && $item['discount'] < 100) {
                    $discounttomoney = intval($item['total_money'] * $item['discount'] / 100);
                }
                $real_total_money = $discounttomoney - $item['discount_money'] + $item['add_fee1'] + $item['add_fee2'];
            }
            $real_total_money = $real_total_money > 0 ? $real_total_money : 0;
            $item['real_total_money'] = $real_total_money;
            $real_total_money_all += $real_total_money;
            $discount_money_all += ($item['total_money'] - $real_total_money);
            $total_money_all += $item['total_money'];
            $goodscount += $item['count'];
            // $goodslist_new[] = $item;
        }


        //赠品
        $sendgoodslist = is_array($req_data['sendgoodslist']) ? $req_data['sendgoodslist'] : (is_array(json_decode($req_data['sendgoodslist'], true)) ? json_decode($req_data['sendgoodslist'], true) : []);
        //校验赠品信息
        $sendgoodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checksendgoods');
        foreach ($sendgoodslist as $sendgoods) {
            if (!$ValidateGoods->check($sendgoods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }
            $sendgoodsinfo = GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'id' => $sendgoods['send_goods_stock_id'], 'is_del' => 1])->first();
            if (!$sendgoodsinfo) {
                return response()->json(['code' => '001', 'msg' => '无效赠品信息']);
            }
            $sendgoodsinfo = $sendgoodsinfo->toArray();

            if ($sendgoodsinfo['count'] < $sendgoods['count']) {
                return response()->json(['code' => '001', 'msg' => '赠品库存不足']);
            }
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'send_goods_stock_id' => $sendgoods['send_goods_stock_id'],
                'count' => $sendgoods['count'],
                'send_goods_info' => json_encode($sendgoodsinfo),
                'goods_sn_code' => $sendgoodsinfo['goods_sn_code'],
                'sendgoods_name' => $sendgoodsinfo['sendgoods_name'],
                'pieceprice' => $sendgoodsinfo['pieceprice'],
            ];
            $sendgoodslist_new[] = $item;
        }

        //旧料
        $recoverygoodslist = is_array($req_data['recoverygoodslist']) ? $req_data['recoverygoodslist'] : (is_array(json_decode($req_data['recoverygoodslist'], true)) ? json_decode($req_data['recoverygoodslist'], true) : []);
        //校验旧料信息

        $recoverygoodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checkrecoverygoods');
        $total_recovery_money = 0;
        foreach ($recoverygoodslist as $recoverygoods) {
            if (!$ValidateGoods->check($recoverygoods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }

            if ($recoverygoods['recovery_type'] == 1) {
                $ValidateSub1 = new ValidateOrderOrderRecovery('subgoods1');
                if (!$ValidateSub1->check($recoverygoods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub1->getError()]);
                }
            }
            if ($recoverygoods['recovery_type'] == 2) {
                $ValidateSub2 = new ValidateOrderOrderRecovery('subgoods2');
                if (!$ValidateSub2->check($recoverygoods)) {
                    return response()->json(['code' => '001', 'msg' => $ValidateSub2->getError()]);
                }
            }

            if ($recoverygoods['change_type'] == 2) {
                if (!isset($recoverygoods['goods_sn_code']) || $recoverygoods['goods_sn_code'] == '') {

                    return response()->json(['code' => '001', 'msg' => '旧料上柜条码不能为空']);
                } else {
                    //查询商品库存是否存在此商品
                    $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'store_id' => $current_store_id, 'is_del' => 1])->first();
                    if (!$isexist) {
                        return response()->json(['code' => '001', 'msg' => '不存在此商品无法上柜']);
                    }
                }
            }

            $goodsinfo = [];
            $recovery_total_netglod_weight = 0;
            if (!empty($recoverygoods['goods_sn_code'])) {
                $salesGoods = OrderSalesGoods::query()
                    ->where('cp_id', $cp_id)
                    ->where('is_del', 1)
                    ->where('order_sn', $recoverygoods['goods_sn_code'])
                    ->orderBy('id', 'desc')
                    ->first();
                $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
                $goodsinfo = empty($salesGoods) ? [] : (array)(json_decode($salesGoods['goodsinfo']));
                $salesGoods['total_netglod_weight'] = 0;
                if (!empty($goodsinfo)) {
                    if ($goodsinfo['is_code_more'] == 2) {
                        $recovery_total_netglod_weight = $recoverygoods['weight'];
                    } else {
                        $recovery_total_netglod_weight = $goodsinfo['netglod_weight'] * $recoverygoods['count'];
                    }
                }

            }


            //$weight =$recoverygoods['weight']-(!empty($recoverygoods['loss_weight'])?$recoverygoods['loss_weight']:0);
            list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsinfo, ['total_netglod_weight' => $recovery_total_netglod_weight]);

            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'money' => $recoverygoods['money'],
                'change_type' => $recoverygoods['change_type'],
                'recovery_type' => $recoverygoods['recovery_type'],
                'goods_category_id' => $recoverygoods['goods_category_id'],
                'goods_catefory_name' => GoodsCategory::where(['cp_id' => $cp_id, 'id' => $recoverygoods['goods_category_id']])->value('category_name'),
                'goods_sn_code' => isset($recoverygoods['goods_sn_code']) ? $recoverygoods['goods_sn_code'] : '',
                'count' => $recoverygoods['count'],
                'weight' => isset($recoverygoods['weight']) ? $recoverygoods['weight'] : 0,
                'price' => isset($recoverygoods['price']) ? $recoverygoods['price'] : 0,
                'd_price' => isset($recoverygoods['d_price']) ? $recoverygoods['d_price'] : 0,
                'discount' => isset($recoverygoods['discount']) ? $recoverygoods['discount'] : 0,
                'dold_price' => isset($recoverygoods['dold_price']) ? $recoverygoods['dold_price'] : 0,
                'dold_fee' => isset($recoverygoods['dold_fee']) ? $recoverygoods['dold_fee'] : 0,
                'loss_weight' => isset($recoverygoods['loss_weight']) ? $recoverygoods['loss_weight'] : 0,
                'remark' => isset($recoverygoods['remark']) ? $recoverygoods['remark'] : '',
                'total_cost_fee' => $deduct_total_cost_fee
            ];
            $recoverygoodslist_new[] = $item;
            $total_recovery_money += $item['money'];
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

        if (!$meminfo) {
            $memdata = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'mobile' => $req_data['mobile'],
                'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                'create_at' => time(),
                'update_at' => time(),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];
            Member::create($memdata);
            $req_data['balance_money'] = 0;
            $req_data['pointstobalance'] = 0;
        } else {
            if (isset($req_data['balance_money']) && $req_data['balance_money'] > $meminfo->pre_money) {
                return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
            } else {
                $req_data['balance_money'] = 0;
            }

            if (isset($req_data['pointstobalance']) && $req_data['pointstobalance'] > $meminfo->pointstobalance) {
                return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
            } else {

                $req_data['pointstobalance'] = 0;
            }
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();
        //主订单计算相关

        $maindata = [
            'cp_id' => $cp_id,
            'store_id' => $current_store_id,
            'mem_id' => $meminfo->id,
            'classesset_id' => $req_data['classesset_id'],
            'order_sn' => date('YmdHis') . $cp_id . $current_store_id . rand(1000, 9999),
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => $req_data['shopping_account_id2'],
            'total_money' => $total_money_all,
            'changegoods_money' => $total_recovery_money,
            'discount_moeny' => $discount_money_all,
            'real_money' => $real_total_money_all,
            'balance_money' => $req_data['balance_money'],
            'pointstobalance' => $req_data['pointstobalance'],
            'pay_money' => $real_total_money_all - $req_data['balance_money'] - $req_data['pointstobalance'],
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']),
            'pay_type_name' => empty($req_data['pay_type_id']) ? '' : ($req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name')),
            'order_at' => isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time(),
            'issendpoints' => $req_data['issendpoints'],
            'coupon_id' => isset($req_data['coupon_id']) ? $req_data['coupon_id'] : 0
        ];
        $maindata['update_account_id'] = $accountinfo['id'];
        $maindata['update_account_real_name'] = $accountinfo['real_name'];
        $maindata['update_at'] = time();
        $maindata['remark'] = isset($req_data['remark']) ? $req_data['remark'] : '';
        //coupon_money
        if (isset($req_data['order_discount']) && intval($req_data['order_discount']) > 0 && intval($req_data['order_discount']) < 100) {
            $real_total_money_all = intval($real_total_money_all * $req_data['order_discount'] / 100);
        }

        if (isset($req_data['order_discount_money']) && intval($req_data['order_discount_money']) > 0 && $maindata['coupon_id'] > 0) {
            return response()->json(['code' => '001', 'msg' => '优惠券不可与整单优惠同时使用']);
        }

        if (isset($req_data['order_discount_money']) && intval($req_data['order_discount_money']) > 0) {
            $real_total_money_all = $real_total_money_all - $req_data['order_discount_money'];
        }
        $coupon_money = 0;
        if ($maindata['coupon_id'] > 0) {
            $coupon_info = WxappCouponCodeList::where([['mem_id', $meminfo->id], ['cp_id', $cp_id], ['id', $maindata['id']], ['is_receive', 2], ['is_used', 1], ['available_end_time', '>=', time()], ['transaction_minimum', '<=', $real_total_money_all]])
                ->where(function ($q) use ($current_store_id) {
                    $store_ids = $current_store_id;
                    $q->where('store_ids', '')->orWhereRaw('FIND_IN_SET(?,store_ids)', [$store_ids]);
                })->first();

            if (!$coupon_info) {
                return response()->json(['code' => '001', 'msg' => '无效优惠券']);
            }
            $coupon_info = $coupon_info->toArray();
            if ($coupon_info['stock_type'] == 'NORMAL') {
                $real_total_money_all = $real_total_money_all - $coupon_info['discount_amount'];
                $coupon_money = $coupon_info['discount_amount'];
            } else {
                $coupon_money = $real_total_money_all - intval($real_total_money_all * $coupon_info['discount_percent'] / 100);
                $real_total_money_all = intval($real_total_money_all * $coupon_info['discount_percent'] / 100);
            }
        }

        if (isset($req_data['round_down_money']) && intval($req_data['round_down_money']) > 0) {
            $maindata['round_down_money'] = $req_data['round_down_money'];
        } else {
            $maindata['round_down_money'] = 0;
        }
        $real_total_money_all = $real_total_money_all - $maindata['round_down_money'];

        $maindata['real_money'] = $real_total_money_all;
        $maindata['coupon_money'] = $coupon_money;
        if ($maindata['balance_money'] > 0 && $maindata['balance_money'] > $real_total_money_all) {
            $maindata['balance_money'] = $real_total_money_all;
            $maindata['pay_money'] = 0;
        } else {
            $maindata['pay_money'] = $real_total_money_all - $req_data['balance_money'];
            if ($req_data['pointstobalance'] > 0 && $req_data['pointstobalance'] > $maindata['pay_money']) {
                $maindata['pointstobalance'] = $maindata['pay_money'];
                $maindata['pay_money'] = 0;
            } else {
                $maindata['pay_money'] = $maindata['pay_money'] - $maindata['pointstobalance'];
            }
        }

        DB::beginTransaction();
        try {
            OrderSales::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->update($maindata);
//            foreach ($goodslist_new as &$gval) {
//                $gval['pid'] = $req_data['id'];
//                $gval['mem_id'] = $meminfo->id;
//                //计算整单优惠拆分
//            }

            foreach ($sendgoodslist_new as &$sgval) {
                $sgval['pid'] = $req_data['id'];
                $sgval['mem_id'] = $meminfo->id;
            }
            foreach ($recoverygoodslist_new as &$rgval) {
                $rgval['pid'] = $req_data['id'];
                $rgval['mem_id'] = $meminfo->id;
            }
            // OrderSalesGoods::insert($goodslist_new);

            OrderSalesSendGoods::where(['pid' => $req_data['id'], 'is_del' => 1])->update(['is_del' => 2, 'del_at' => time()]);
            OrderSalesRecoveryGoods::where(['pid' => $req_data['id'], 'is_del' => 1])->update(['is_del' => 2, 'del_at' => time()]);

            count($sendgoodslist_new) > 0 && OrderSalesSendGoods::insert($sendgoodslist_new);
            count($recoverygoodslist_new) > 0 && OrderSalesRecoveryGoods::insert($recoverygoodslist_new);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '创建订单失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '创建订单成功']);
    }

    /**
     * 审核通过
     */
    public function doorderauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }

        if ($info->is_maker != 1 && $info->is_maker != 0) {
            return response()->json(['code' => '001', 'msg' => '该订单挂单中或挂单取消不可审核']);
        }

        $meminfo = Member::query()->where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();

        if (!empty($meminfo) && $meminfo->id > 0) {
            if ($info->balance_money > 0) {
                if ($info->balance_money > $meminfo->pre_money) {
                    return response()->json(['code' => '001', 'msg' => '预存金额不足']);
                }
            }

            if ($info->pointstobalance > 0) {
                if ($info->pointstobalance > $meminfo->pointstobalance) {
                    return response()->json(['code' => '001', 'msg' => '积分金额不足']);
                }
            }
        }


        DB::beginTransaction();
        try {

            if ($info->mem_id > 0 && ($info->balance_money > 0 || $info->pointstobalance > 0) && !empty($meminfo)) {
                $data = [
                    'cp_id' => $cp_id,
                    'mem_id' => $info->mem_id,
                    'type' => 12,
                    'store_id' => $info->store_id,
                    'change_val' => -$info->balance_money,
                    'change_before' => $meminfo->pre_money,
                    'change_after' => $meminfo->pre_money - $info->balance_money,
                    'sales_account_id' => $info->shopping_account_id1,
                    'loginfo' => json_encode(['title' => '销售开单']),
                    'create_account_id' => $info->create_account_id,
                    'update_account_id' => $info->update_account_id,
                    'create_account_real_name' => $info->create_account_real_name,
                    'update_account_real_name' => $info->update_account_real_name,
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark' => $info->remark,
                ];
                MemberBalanceChangelog::create($data);
                Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'pre_money' => DB::raw('pre_money - ' . $info->balance_money),
                    'pointstobalance' => DB::raw('pointstobalance - ' . $info->pointstobalance)
                ]);
            }


            OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time(),'update_at'=>time()]);


            OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_at' => time()]);
            OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
            OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
            OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);

            //会员处理
            if ($info->mem_id > 0 && !empty($meminfo)) {
                Member::query()->where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'shopping_times' => DB::raw('shopping_times + 1 '),
                    'shopping_money_total' => DB::raw('shopping_money_total + ' . $info->real_money),
                    'avg_shopping_money' => intval(($meminfo->shopping_money_total + $info->real_money) / ($meminfo->shopping_times + 1)),
                    'max_shopping_money' => ($info->real_money > $meminfo->max_shopping_money ? $info->real_money : $meminfo->max_shopping_money),
                    'min_shopping_money' => ($info->real_money < $meminfo->min_shopping_money ? $info->real_money : $meminfo->min_shopping_money),
                    'last_shopping_at' => $info->create_at
                ]);
            }

            if (!empty($meminfo) && $info->real_money > 0 && $info->mem_id > 0 && $info->issendpoints == 2 && $meminfo->share_mem_id > 0 && $info->share_mem_send_points > 0) {
                //消费记录记录全部的消费类型
                // 推荐人积分只有在会员第一次下时才加积分
                $salesshopping_times = OrderSales::where(['mem_id' => $info->mem_id, 'audit_status' => 2, 'cp_id' => $cp_id, 'is_del' => 1])->count();
                if ($salesshopping_times == 1) {
                    $share_mem_info = Member::where(['cp_id' => $cp_id, 'id' => $meminfo->share_mem_id, 'is_del' => 1])->first();
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $meminfo->share_mem_id,
                        'type' => 3,
                        'store_id' => $info->store_id,
                        'change_val' => $info->share_mem_send_points,
                        'change_before' => $share_mem_info->points_current,
                        'change_after' => $share_mem_info->points_current + $info->share_mem_send_points,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '推荐积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '推荐积分',
                    ];
                    MemberPointsChangelog::create($data);
                    Member::where(['id' => $share_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total + ' . $info->share_mem_send_points),
                        'points_current' => DB::raw('points_current + ' . $info->share_mem_send_points)
                    ]);
                    CommonMember::checkMemLv($share_mem_info->id);//会员升级
                }


            }

            if (!empty($meminfo) && $info->mem_id > 0 && $info->issendpoints == 2 && ($info->order_points > 0 || $info->order_points_recovery > 0)) {
                $data = [
                    'cp_id' => $cp_id,
                    'mem_id' => $meminfo->id,
                    'type' => 3,
                    'store_id' => $info->store_id,
                    'change_val' => ($info->order_points_recovery + $info->order_points),
                    'change_before' => $meminfo->points_current,
                    'change_after' => $meminfo->points_current + ($info->order_points_recovery + $info->order_points),
                    'sales_account_id' => $info->shopping_account_id1,
                    'loginfo' => json_encode(['title' => '购物赠送积分']),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark' => '购物赠送积分',
                ];
                MemberPointsChangelog::create($data);
                Member::where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'points_total' => DB::raw('points_total + ' . ($info->order_points_recovery + $info->order_points)),
                    'points_current' => DB::raw('points_current + ' . ($info->order_points_recovery + $info->order_points))
                ]);
                CommonMember::checkMemLv($meminfo->id);//会员升级
            }


            //核销优惠券
            if (!empty($meminfo) && $info->mem_id > 0 && $info->coupon_id > 0) {
                $Wxcoupon = new Wxcoupon($cp_id);
                $Wxcoupon->checkputcoupon($info->coupon_id, $id);
            }


            //截金处理
            $truncate_glod_list = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'is_gram' => 1])->where([['truncate_glod_weight', '>', 0], ['truncate_glod_money', '>', 0]])->get()->toArray();
            foreach ($truncate_glod_list as $truncate_glod) {
                $goodsinfo = json_decode($truncate_glod['goodsinfo'], true);
                $truncate_glod_data = $goodsinfo;

                $truncate_glod_data['remark'] = '截金处理';
                $truncate_glod_data['count'] = $truncate_glod['count'];
                $truncate_glod_data['stock_type'] = 3;
                unset($truncate_glod_data['allot_count']);
                unset($truncate_glod_data['sales_count']);
                unset($truncate_glod_data['id']);
                unset($truncate_glod_data['start_stockin_store_id']);
                unset($truncate_glod_data['is_del']);
                unset($truncate_glod_data['del_at']);

                unset($truncate_glod_data['pricetype']);
                unset($truncate_glod_data['odds']);

                unset($truncate_glod_data['storeinfo']);
                unset($truncate_glod_data['startstoreinfo']);
                unset($truncate_glod_data['goods_category']);
                unset($truncate_glod_data['supply']);
                unset($truncate_glod_data['goods_style']);
                unset($truncate_glod_data['goods_craft']);
                unset($truncate_glod_data['goods_pricetype']);
                unset($truncate_glod_data['goods_stone']);
                unset($truncate_glod_data['paytype_info']);
                unset($truncate_glod_data['goods_brand']);
                $truncate_glod_data['back_company_price'] = $truncate_glod['old_recovery_price'];
                $truncate_glod_data['netglod_weight'] = $truncate_glod['truncate_glod_weight'];
                $truncate_glod_data['netglod_weight_new'] = $truncate_glod['truncate_glod_weight'];
                $truncate_glod_data['old_recovery_price'] = $truncate_glod['old_recovery_price'];
                $truncate_glod_data['piece_weight'] = $truncate_glod['truncate_glod_weight'];
                $truncate_glod_data['piece_weight_new'] = $truncate_glod['truncate_glod_weight'];

                $truncate_glod_data['type'] = 4;
                $truncate_glod_data['create_at'] = time();
                $truncate_glod_data['update_at'] = time();
                $truncate_glod_data['create_account_id'] = $accountinfo['id'];
                $truncate_glod_data['update_account_id'] = $accountinfo['id'];
                $truncate_glod_data['create_account_real_name'] = $accountinfo['real_name'];
                $truncate_glod_data['update_account_real_name'] = $accountinfo['real_name'];
                $truncate_glod_data['order_sncode'] = $info->order_sn;
                $truncate_glod_data['stockin_at'] = time();
                $truncate_glod_data['audit_status'] = 2;
                $truncate_glod_data['exchange_amount'] = intval($truncate_glod['truncate_glod_weight'] * $truncate_glod['old_recovery_price']);

                Stock::create($truncate_glod_data);
                //旧料日志
                $oldLog = [];
                $oldLog['cp_id'] = $cp_id;
                $oldLog['store_id'] = $truncate_glod_data['store_id'];
                $oldLog['start_store_id'] = $truncate_glod_data['store_id'];
                $oldLog['target_store_id'] = $truncate_glod_data['store_id'];
                $oldLog['order_sncode'] = $truncate_glod_data['order_sncode'];
                $oldLog['goods_category_id'] = $truncate_glod_data['goods_category_id'];
                $oldLog['stock_type'] = $truncate_glod_data['stock_type'];
                $oldLog['piece_weight'] = $truncate_glod_data['netglod_weight_new'];
                $oldLog['count'] = $truncate_glod_data['count'];
                $oldLog['cf_no'] = $truncate_glod_data['cf_no'] ?? '';
                $oldLog['create_account_id'] = $truncate_glod_data['create_account_id'];
                $oldLog['create_account_real_name'] = $truncate_glod_data['create_account_real_name'];
                $oldLog['create_at'] = $truncate_glod_data['create_at'];

                (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 9);
            }

            //旧料处理
            $recoverygoodslist = OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();
            foreach ($recoverygoodslist as $recoverygoods) {

                if ($recoverygoods['change_type'] == 1) {
                    //添加到旧料
                    $oldmaterialstockdata = [];
                    $infobygoods_sn_code = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                    if ($infobygoods_sn_code) {
                        $oldmaterialstockdata = $infobygoods_sn_code->toArray();
                        $oldmaterialstockdata['store_id'] = $info->store_id;
                        $oldmaterialstockdata['count'] = $recoverygoods['count'];
                        $oldmaterialstockdata['cp_id'] = $cp_id;
                        unset($oldmaterialstockdata['id']);
                    } else {
                        $oldmaterialstockdata['cp_id'] = $cp_id;
                        $oldmaterialstockdata['store_id'] = $info->store_id;
                        $oldmaterialstockdata['count'] = $recoverygoods['count'];
                        $oldmaterialstockdata['goods_sn_code'] = $recoverygoods['goods_sn_code'];
                        $oldmaterialstockdata['goods_category_id'] = $recoverygoods['goods_category_id'];
                    }
                    $oldmaterialstockdata['order_sncode'] = $info->order_sn;
                    $oldmaterialstockdata['stockin_at'] = time();
                    $oldmaterialstockdata['create_at'] = time();
                    $oldmaterialstockdata['type'] = 1;
                    $oldmaterialstockdata['stock_type'] = $recoverygoods['recovery_type'];
                    // 一码多货的总金重和件重商品都是piece_weight终端
                    $oldmaterialstockdata['piece_weight'] = $recoverygoods['weight'] * $recoverygoods['count'];
                    $oldmaterialstockdata['piece_weight_new'] = ($recoverygoods['weight'] - $recoverygoods['loss_weight']) * $recoverygoods['count'];
                    $oldmaterialstockdata['back_company_price'] = $recoverygoods['old_recovery_price'];
                    $oldmaterialstockdata['label_price'] = $recoverygoods['d_price'];
                    $oldmaterialstockdata['exchange_amount'] = $recoverygoods['money'];
                    $oldmaterialstockdata['remark'] = $recoverygoods['remark'];
                    $oldmaterialstockdata['create_account_id'] = $accountinfo['id'];
                    $oldmaterialstockdata['update_account_id'] = $accountinfo['id'];
                    $oldmaterialstockdata['create_account_real_name'] = $accountinfo['real_name'];
                    $oldmaterialstockdata['update_account_real_name'] = $accountinfo['real_name'];
                    $oldmaterialstockdata['dold_fee'] = $recoverygoods['dold_fee'];
                    $oldmaterialstockdata['audit_status'] = 2;
                    $oldmaterialstockdata['valuations'] = $recoverygoods['valuations'];
                    $oldmaterialstockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                    Stock::query()->create($oldmaterialstockdata);
                    //旧料日志
                    $oldLog = [];
                    $oldLog['cp_id'] = $oldmaterialstockdata['cp_id'];
                    $oldLog['store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['start_store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['target_store_id'] = $oldmaterialstockdata['store_id'];
                    $oldLog['order_sncode'] = $oldmaterialstockdata['order_sncode'];
                    $oldLog['goods_category_id'] = $oldmaterialstockdata['goods_category_id'];
                    $oldLog['stock_type'] = $oldmaterialstockdata['stock_type'];
                    $oldLog['piece_weight'] = $oldmaterialstockdata['piece_weight'];
                    $oldLog['count'] = $oldmaterialstockdata['count'];
                    $oldLog['cf_no'] = $oldmaterialstockdata['cf_no'] ?? '';
                    $oldLog['create_account_id'] = $oldmaterialstockdata['create_account_id'];
                    $oldLog['create_account_real_name'] = $oldmaterialstockdata['create_account_real_name'];
                    $oldLog['create_at'] = $oldmaterialstockdata['create_at'];

                    (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 8);

                } else {
                    //上柜
                    $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();

                    if ($goodsStock) {
                        $goodsStock = $goodsStock->toArray();

                        //recovery_type =1按克，2标价
                        $is_gram = GoodsCategory::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                            ->where('id', $goodsStock['goods_category_id'])
                            ->value('is_gram') ?? 0;

                        $recovery_total_netglod_weight = 0;
                        $count = $goodsStock['count'] + $recoverygoods['count'];
                        if ($recoverygoods['recovery_type'] == 1) {
                            if ($goodsStock['is_code_more'] == 2) {
                                $log_total_netglod_weight = $recoverygoods['weight'];
                                $log_total_piece_weight = 0;

                                $total_netglod_weight = $goodsStock['total_netglod_weight'] + $recoverygoods['weight'];
                                $total_piece_weight = 0;

                                $recovery_total_netglod_weight = $recoverygoods['weight'];
                            } else {
                                // 非一码多货
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                $recovery_total_netglod_weight = $log_total_netglod_weight;
                            }
                        } else {
                            $total_piece_weight = $goodsStock['piece_weight'] * $count;
                            $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                            $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                            $log_total_netglod_weigh = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                            $recovery_total_netglod_weight = $log_total_netglod_weigh;
                        }
                        $recoverygoods['total_netglod_weight'] = $recovery_total_netglod_weight;
                        list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($goodsStock, $recoverygoods, $is_gram);

                        $goodsStock['count'] = $count;
                        $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                        $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;

                        // $total_cost_fee =(new Goods())->computeOriginalTotalCost($goodsStock,$is_gram);
                        $stockArr = [
                            'count' => $count,
                            'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                            'total_piece_weight' => $goodsStock['total_piece_weight'],
                            'total_cost_fee' => $total_cost_fee,
                            'costglod_price' => $costglod_price,
                            'piececost_fee' => $piececost_fee
                        ];
                        GoodsStockList::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])
                            ->update($stockArr);

                        $stockdata = $goodsStock;
                        $stockdata['count'] = $recoverygoods['count'];
                        $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                        $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;

                        $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                        $stockdata['costglod_price'] = $costglod_price ?? 0;
                        $stockdata['piececost_fee'] = $piececost_fee ?? 0;
                        Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 93, $info->order_sn);

                    } else {
                        $goodsStock = GoodsStockList::query()->where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if (empty($goodsStock)) {
                            return response()->json(['code' => '001', 'msg' => '商品' . $recoverygoods['goods_sn_code'] . '不存在无法上柜']);
                        }
                        $goodsStock = $goodsStock->toArray();

                        // 一下数据从新赋值，再写入商品库存
                        $stockdata = $goodsStock;
                        $stockdata['store_id'] = $info->store_id;
                        $stockdata['count'] = $recoverygoods['count'];
                        $stockdata['allot_count'] = 0;
                        $stockdata['sales_count'] = 0;
                        $stockdata['start_stockin_store_id'] = $info->store_id;
                        $stockdata['stockin_at'] = time();
                        $stockdata['create_at'] = time();

                        if ($recoverygoods['recovery_type'] == 1) {
                            if ($goodsStock['is_code_more'] == 2) {
                                $total_netglod_weight = $recoverygoods['weight'];
                            } else {
                                // 非一码多货
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $stockdata['count'];
                                $total_piece_weight = $goodsStock['piece_weight'] * $stockdata['count'];
                            }
                        } else {
                            $total_netglod_weight = $goodsStock['netglod_weight'] * $stockdata['count'];
                            $total_piece_weight = $goodsStock['piece_weight'] * $stockdata['count'];
                        }
                        $is_gram = GoodsCategory::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                            ->where('id', $goodsStock['goods_category_id'])
                            ->value('is_gram') ?? 0;

                        $stockdata['total_netglod_weight'] = $total_netglod_weight ?? 0;
                        $stockdata['total_piece_weight'] = $total_piece_weight ?? 0;
                        // 此处总成本需要取旧料的总成本
                        $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                        $stockdata['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($stockdata, $is_gram);
                        unset($stockdata['id']);
                        GoodsStockList::query()->create($stockdata);
                        Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 93, $info->order_sn);
                    }

                }


            }
            //收支流水
            Financial::createMoneyLog($cp_id, $info, $info->pay_money, -1);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            info('审核失败' . $e->getFile() . $e->getLine() . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '审核失败']);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);


    }


    public function doorderauditsuccessmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info_more_arr = OrderSales::where(['cp_id' => $cp_id, 'audit_status' => 1])->whereIn('is_maker', [1, 0])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核或未支付订单']);
        }
        DB::beginTransaction();
        try {

            foreach ($info_more_arr as $info) {

                $id = $info->id;
                $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();
                $msgtitle = '订单：' . $info->order_sn;
                if ($meminfo && $meminfo->id > 0) {
                    if ($info->balance_money > 0) {
                        if ($info->balance_money > $meminfo->pre_money) {
                            // return response()->json(['code' => '001', 'msg' => '预存金额不足']);
                            throw new \Exception($msgtitle . '预存金额不足');
                        }
                    }

                    if ($info->pointstobalance > 0) {
                        if ($info->pointstobalance > $meminfo->pointstobalance) {
                            // return response()->json(['code' => '001', 'msg' => '积分金额不足']);
                            throw new \Exception($msgtitle . '积分金额不足');
                        }
                    }
                }
                if ($info->mem_id > 0 && ($info->balance_money > 0 || $info->pointstobalance > 0)) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $info->mem_id,
                        'type' => 12,
                        'store_id' => $info->store_id,
                        'change_val' => -$info->balance_money,
                        'change_before' => $meminfo->pre_money,
                        'change_after' => $meminfo->pre_money - $info->balance_money,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '销售开单']),
                        'create_account_id' => $info->create_account_id,
                        'update_account_id' => $info->update_account_id,
                        'create_account_real_name' => $info->create_account_real_name,
                        'update_account_real_name' => $info->update_account_real_name,
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => $info->remark,
                    ];
                    MemberBalanceChangelog::create($data);
                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'pre_money' => DB::raw('pre_money - ' . $info->balance_money),
                        'pointstobalance' => DB::raw('pointstobalance - ' . $info->pointstobalance)
                    ]);
                }


                OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time(),'update_at'=>time()]);


                OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_at' => time()]);
                OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
                OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
                OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);
                //会员处理

                $info->mem_id > 0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'shopping_times' => DB::raw('shopping_times + 1 '),
                    'shopping_money_total' => DB::raw('shopping_money_total + ' . $info->real_money),
                    'avg_shopping_money' => intval(($meminfo->shopping_money_total + $info->real_money) / ($meminfo->shopping_times + 1)),
                    'max_shopping_money' => ($info->real_money > $meminfo->max_shopping_money ? $info->real_money : $meminfo->max_shopping_money),
                    'min_shopping_money' => ($info->real_money < $meminfo->min_shopping_money ? $info->real_money : $meminfo->min_shopping_money),
                    'last_shopping_at' => $info->create_at
                ]);
                if ($info->mem_id > 0 && $info->issendpoints == 2 && $meminfo->share_mem_id > 0 && $info->share_mem_send_points > 0) {//&& $meminfo->shopping_times<=0 消费记录记录全部的消费类型

                    $salesshopping_times = OrderSales::where(['mem_id' => $info->mem_id, 'audit_status' => 2, 'cp_id' => $cp_id, 'is_del' => 1])->count();
                    if ($salesshopping_times == 1) {
                        $share_mem_info = Member::where(['cp_id' => $cp_id, 'id' => $meminfo->share_mem_id, 'is_del' => 1])->first();
                        $data = [
                            'cp_id' => $cp_id,
                            'mem_id' => $meminfo->share_mem_id,
                            'type' => 3,
                            'store_id' => $info->store_id,
                            'change_val' => $info->share_mem_send_points,
                            'change_before' => $share_mem_info->points_current,
                            'change_after' => $share_mem_info->points_current + $info->share_mem_send_points,
                            'sales_account_id' => $info->shopping_account_id1,
                            'loginfo' => json_encode(['title' => '推荐积分']),
                            'create_account_id' => $accountinfo['id'],
                            'update_account_id' => $accountinfo['id'],
                            'create_account_real_name' => $accountinfo['real_name'],
                            'update_account_real_name' => $accountinfo['real_name'],
                            'create_at' => time(),
                            'update_at' => time(),
                            'remark' => '推荐积分',
                        ];
                        MemberPointsChangelog::create($data);
                        Member::where(['id' => $share_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                            'points_total' => DB::raw('points_total + ' . $info->share_mem_send_points),
                            'points_current' => DB::raw('points_current + ' . $info->share_mem_send_points)
                        ]);
                        CommonMember::checkMemLv($share_mem_info->id);//会员升级
                    }


                }

                if ($info->mem_id > 0 && $info->issendpoints == 2 && ($info->order_points > 0 || $info->order_points_recovery > 0)) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $meminfo->id,
                        'type' => 3,
                        'store_id' => $info->store_id,
                        'change_val' => ($info->order_points_recovery + $info->order_points),
                        'change_before' => $meminfo->points_current,
                        'change_after' => $meminfo->points_current + ($info->order_points_recovery + $info->order_points),
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '购物赠送积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '购物赠送积分',
                    ];
                    MemberPointsChangelog::create($data);
                    Member::where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total + ' . ($info->order_points_recovery + $info->order_points)),
                        'points_current' => DB::raw('points_current + ' . ($info->order_points_recovery + $info->order_points))
                    ]);
                    CommonMember::checkMemLv($meminfo->id);//会员升级
                }


                //核销优惠券
                if ($info->mem_id > 0 && $info->coupon_id > 0) {
                    $Wxcoupon = new Wxcoupon($cp_id);
                    $Wxcoupon->checkputcoupon($info->coupon_id, $id);
                }


                //截金处理
                $truncate_glod_list = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'is_gram' => 1])->where([['truncate_glod_weight', '>', 0], ['truncate_glod_money', '>', 0]])->get()->toArray();
                foreach ($truncate_glod_list as $truncate_glod) {
                    $goodsinfo = json_decode($truncate_glod['goodsinfo'], true);
                    $truncate_glod_data = $goodsinfo;

                    $truncate_glod_data['remark'] = '截金处理';
                    $truncate_glod_data['count'] = $truncate_glod['count'];
                    $truncate_glod_data['stock_type'] = 1;
                    unset($truncate_glod_data['allot_count']);
                    unset($truncate_glod_data['sales_count']);
                    unset($truncate_glod_data['id']);
                    unset($truncate_glod_data['start_stockin_store_id']);
                    unset($truncate_glod_data['is_del']);
                    unset($truncate_glod_data['del_at']);

                    unset($truncate_glod_data['pricetype']);
                    unset($truncate_glod_data['odds']);

                    unset($truncate_glod_data['storeinfo']);
                    unset($truncate_glod_data['startstoreinfo']);
                    unset($truncate_glod_data['goods_category']);
                    unset($truncate_glod_data['supply']);
                    unset($truncate_glod_data['goods_style']);
                    unset($truncate_glod_data['goods_craft']);
                    unset($truncate_glod_data['goods_pricetype']);
                    unset($truncate_glod_data['goods_stone']);
                    unset($truncate_glod_data['paytype_info']);
                    unset($truncate_glod_data['goods_brand']);
                    $truncate_glod_data['back_company_price'] = $truncate_glod['old_recovery_price'];
                    $truncate_glod_data['netglod_weight'] = $truncate_glod['truncate_glod_weight'];
                    $truncate_glod_data['netglod_weight_new'] = $truncate_glod['truncate_glod_weight'];
                    $truncate_glod_data['old_recovery_price'] = $truncate_glod['old_recovery_price'];
                    $truncate_glod_data['piece_weight'] = $truncate_glod['truncate_glod_weight'];
                    $truncate_glod_data['piece_weight_new'] = $truncate_glod['truncate_glod_weight'];

                    $truncate_glod_data['type'] = 4;
                    $truncate_glod_data['create_at'] = time();
                    $truncate_glod_data['update_at'] = time();
                    $truncate_glod_data['create_account_id'] = $accountinfo['id'];
                    $truncate_glod_data['update_account_id'] = $accountinfo['id'];
                    $truncate_glod_data['create_account_real_name'] = $accountinfo['real_name'];
                    $truncate_glod_data['update_account_real_name'] = $accountinfo['real_name'];
                    $truncate_glod_data['order_sncode'] = $info->order_sn;
                    $truncate_glod_data['stockin_at'] = time();
                    $truncate_glod_data['audit_status'] = 2;
                    $truncate_glod_data['exchange_amount'] = intval($truncate_glod['truncate_glod_weight'] * $truncate_glod['old_recovery_price']);

                    Stock::create($truncate_glod_data);
                    //旧料日志
                    $oldLog = [];
                    $oldLog['cp_id'] = $cp_id;
                    $oldLog['store_id'] = $truncate_glod_data['store_id'];
                    $oldLog['start_store_id'] = $truncate_glod_data['store_id'];
                    $oldLog['target_store_id'] = $truncate_glod_data['store_id'];
                    $oldLog['order_sncode'] = $truncate_glod_data['order_sncode'];
                    $oldLog['goods_category_id'] = $truncate_glod_data['goods_category_id'];
                    $oldLog['stock_type'] = $truncate_glod_data['stock_type'];
                    $oldLog['piece_weight'] = $truncate_glod_data['netglod_weight_new'];
                    $oldLog['count'] = $truncate_glod_data['count'];
                    $oldLog['cf_no'] = $truncate_glod_data['cf_no'];
                    $oldLog['create_account_id'] = $truncate_glod_data['create_account_id'];
                    $oldLog['create_account_real_name'] = $truncate_glod_data['create_account_real_name'];
                    $oldLog['create_at'] = $truncate_glod_data['create_at'];

                    (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 9);
                }


                //旧料处理
                $recoverygoodslist = OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();
                foreach ($recoverygoodslist as $recoverygoods) {
                    if ($recoverygoods['change_type'] == 1) {
                        //添加到旧料
                        $oldmaterialstockdata = [];
                        $infobygoods_sn_code = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if ($infobygoods_sn_code) {
                            $oldmaterialstockdata = $infobygoods_sn_code->toArray();
                            $oldmaterialstockdata['store_id'] = $info->store_id;
                            $oldmaterialstockdata['count'] = $recoverygoods['count'];
                            $oldmaterialstockdata['cp_id'] = $cp_id;

                            unset($oldmaterialstockdata['id']);
                        } else {

                            $oldmaterialstockdata['cp_id'] = $cp_id;
                            $oldmaterialstockdata['store_id'] = $info->store_id;
                            $oldmaterialstockdata['count'] = $recoverygoods['count'];
                            $oldmaterialstockdata['goods_sn_code'] = $recoverygoods['goods_sn_code'];
                            $oldmaterialstockdata['goods_category_id'] = $recoverygoods['goods_category_id'];
                        }
                        $oldmaterialstockdata['order_sncode'] = $info->order_sn;
                        $oldmaterialstockdata['stockin_at'] = time();
                        $oldmaterialstockdata['create_at'] = time();
                        $oldmaterialstockdata['type'] = 1;
                        $oldmaterialstockdata['stock_type'] = $recoverygoods['recovery_type'];
                        $oldmaterialstockdata['piece_weight'] = $recoverygoods['weight'] * $recoverygoods['count'];
                        $oldmaterialstockdata['piece_weight_new'] = ($recoverygoods['weight'] - $recoverygoods['loss_weight']) * $recoverygoods['count'];
                        $oldmaterialstockdata['back_company_price'] = $recoverygoods['old_recovery_price'];
                        $oldmaterialstockdata['label_price'] = $recoverygoods['d_price'];
                        $oldmaterialstockdata['exchange_amount'] = $recoverygoods['money'];
                        $oldmaterialstockdata['remark'] = $recoverygoods['remark'];
                        $oldmaterialstockdata['create_account_id'] = $accountinfo['id'];
                        $oldmaterialstockdata['update_account_id'] = $accountinfo['id'];
                        $oldmaterialstockdata['create_account_real_name'] = $accountinfo['real_name'];
                        $oldmaterialstockdata['update_account_real_name'] = $accountinfo['real_name'];
                        $oldmaterialstockdata['dold_fee'] = $recoverygoods['dold_fee'];
                        $oldmaterialstockdata['audit_status'] = 2;
                        $oldmaterialstockdata['valuations'] = $recoverygoods['valuations'];
                        $oldmaterialstockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                        Stock::create($oldmaterialstockdata);


                        //旧料日志
                        $oldLog = [];
                        $oldLog['cp_id'] = $oldmaterialstockdata['cp_id'];
                        $oldLog['store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['start_store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['target_store_id'] = $oldmaterialstockdata['store_id'];
                        $oldLog['order_sncode'] = $oldmaterialstockdata['order_sncode'];
                        $oldLog['goods_category_id'] = $oldmaterialstockdata['goods_category_id'];
                        $oldLog['stock_type'] = $oldmaterialstockdata['stock_type'];
                        $oldLog['piece_weight'] = $oldmaterialstockdata['piece_weight'];
                        $oldLog['count'] = $oldmaterialstockdata['count'];
                        $oldLog['cf_no'] = $oldmaterialstockdata['cf_no'] ?? '';
                        $oldLog['create_account_id'] = $oldmaterialstockdata['create_account_id'];
                        $oldLog['create_account_real_name'] = $oldmaterialstockdata['create_account_real_name'];
                        $oldLog['create_at'] = $oldmaterialstockdata['create_at'];

                        (new \App\Store\Models\OldMaterial\Log())->addLog($oldLog, 8);

                    } else {
                        //上柜
                        $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if ($goodsStock) {
                            $goodsStock = $goodsStock->toArray();
                            //recovery_type =1按克，2标价
                            $is_gram = GoodsCategory::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                                ->where('id', $goodsStock['goods_category_id'])
                                ->value('is_gram') ?? 0;

                            $count = $goodsStock['count'] + $recoverygoods['count'];
                            $recoverygoods['total_netglod_weight'] = 0;
                            if ($recoverygoods['recovery_type'] == 1) {
                                if ($goodsStock['is_code_more'] == 2) {
                                    $log_total_netglod_weight = $recoverygoods['weight'];
                                    $log_total_piece_weight = 0;

                                    $total_piece_weight = 0;
                                    $total_netglod_weight = $goodsStock['total_netglod_weight'] + $recoverygoods['weight'];
                                    $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                                } else {
                                    // 非一码多货
                                    $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                    $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                    $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                    $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                    $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                                }
                            } else {

                                $total_piece_weight = $goodsStock['piece_weight'] * $count;
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                                $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight;
                            }

                            list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($goodsStock, $recoverygoods, $is_gram);

                            $goodsStock['count'] = $count;
                            $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                            $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;

                            // $total_cost_fee =(new Goods())->computeOriginalTotalCost($goodsStock,$is_gram);
                            $stockArr = [
                                'count' => $count,
                                'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                                'total_piece_weight' => $goodsStock['total_piece_weight'],
                                'total_cost_fee' => $total_cost_fee,
                                'costglod_price' => $costglod_price,
                                'piececost_fee' => $piececost_fee
                            ];
                            GoodsStockList::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])
                                ->update($stockArr);

                            $stockdata = $goodsStock;
                            $stockdata['count'] = $recoverygoods['count'];
                            $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                            $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;
                            $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                            $stockdata['costglod_price'] = $costglod_price ?? 0;
                            $stockdata['piececost_fee'] = $piececost_fee ?? 0;
                            Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 93, $info->order_sn);

                        } else {
                            $goodsStock = GoodsStockList::query()->where(['cp_id' => $cp_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                            if (empty($goodsStock)) {
                                return response()->json(['code' => '001', 'msg' => '商品' . $recoverygoods['goods_sn_code'] . '不存在无法上柜']);
                            }
                            $goodsStock = $goodsStock->toArray();
                            $is_gram = GoodsCategory::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                                ->where('id', $goodsStock['goods_category_id'])
                                ->value('is_gram') ?? 0;


                            // 一下数据从新赋值，再写入商品库存
                            $stockdata = $goodsStock;
                            $stockdata['store_id'] = $info->store_id;
                            $stockdata['count'] = $recoverygoods['count'];
                            $stockdata['allot_count'] = 0;
                            $stockdata['sales_count'] = 0;
                            $stockdata['start_stockin_store_id'] = $info->store_id;
                            $stockdata['stockin_at'] = time();
                            $stockdata['create_at'] = time();

                            if ($recoverygoods['recovery_type'] == 1) {
                                if ($goodsStock['is_code_more'] == 2) {
                                    $total_netglod_weight = $recoverygoods['weight'];
                                } else {
                                    // 非一码多货
                                    $total_netglod_weight = $goodsStock['netglod_weight'] * $stockdata['count'];
                                    $total_piece_weight = $goodsStock['piece_weight'] * $stockdata['count'];
                                }
                            } else {
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $stockdata['count'];
                                $total_piece_weight = $goodsStock['piece_weight'] * $stockdata['count'];
                            }

                            $stockdata['total_netglod_weight'] = $total_netglod_weight ?? 0;
                            $stockdata['total_piece_weight'] = $total_piece_weight ?? 0;
                            $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                            $stockdata['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($stockdata, $is_gram);
                            unset($stockdata['id']);
                            GoodsStockList::query()->create($stockdata);
                            Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 93, $info->order_sn);
                        }
                    }


                }
                //收支流水
                Financial::createMoneyLog($cp_id, $info, $info->pay_money, -1);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getLine() . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);


    }


    /**
     * 审核取消
     *
     * 2024.11.28 撤单后，需要删除旧料库存 截金数据，使用 order_sn查询
     */
    public function doorderauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $audit_remark = $request->audit_remark ?? '';
        if ($audit_remark == '') {
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if (($accountinfo['type'] == 1 || $accountinfo['type'] == 2) && date('Y-m-d', $info->create_at) != date('Y-m-d') && $info->audit_status == 2) {
            return response()->json(['code' => '001', 'msg' => '店长只可撤单当日已审核订单']);
        }


        if ($info->is_maker != 1 && $info->is_maker != 0) {
            return response()->json(['code' => '001', 'msg' => '该订单挂单中或挂单取消不可审核']);
        }
        $goodslist = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'red_status' => 1])->get()->toArray();

        if (empty($goodslist)) {
            return response()->json(['code' => '001', 'msg' => '商品信息不存在或者存在红冲商品，不能撤单']);
        }

        $sendgoodslist = OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();

        if ($info->audit_status != 1 && $info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '订单已经撤销']);
        }
        //旧料表
        $oldmaterialcount = Stock::query()
            ->where(['order_sncode' => $info->order_sn, 'cp_id' => $cp_id])
            ->get()
            ->toArray();
        if (!empty($oldmaterialcount)) {
            foreach ($oldmaterialcount as $v) {
                if ($v['is_del'] == 2 || $v['stock_status'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单下的旧料不在库，不支持撤单']);
                }
            }
        }


        //旧料库存表
        $recoverygoodslist = OrderSalesRecoveryGoods::query()->where(['pid' => $id, 'is_del' => 1])->get()->toArray();
        foreach ($recoverygoodslist as $recoverygoods) {
            if ($recoverygoods['change_type'] != 1) {
                //上柜
                $goodinfo = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])
                    ->select(['total_netglod_weight', 'total_piece_weight', 'is_del'])
                    ->first()
                    ->toArray();
                if ($goodinfo['is_del'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                }
                $recoverygoodsweight = $recoverygoods['weight'] * $recoverygoods['count'];
                if ($recoverygoods['recovery_type'] == 1) {
                    //total_netglod_weight
                    if ($recoverygoodsweight > $goodinfo['total_netglod_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                } else {
                    //total_piece_weight
                    if ($recoverygoodsweight > $goodinfo['total_piece_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                }
            }

        }

        DB::beginTransaction();
        try {

            $goodsIds = array_column($goodslist, 'goods_stock_id');
            $goodsStock = (new GoodsStockList())->getGoodsStockByIds($cp_id, $goodsIds);
            foreach ($goodslist as $val) {
                $goods = $goodsStock[$val['goods_stock_id']] ?? [];

                if ($goods['is_code_more'] == 2) {
                    $stockData = [
                        'count' => $goods['count'] + $val['count'],
                        'sales_count' => $goods['sales_count'] - $val['count']
                    ];
                    $stockData['total_netglod_weight'] = $goods['total_netglod_weight'] + $val['weight'];
                    $val['total_netglod_weight'] = $val['weight'];
//                    GoodsStockList::where(['cp_id' => $cp_id, 'id' => $val['goods_stock_id'], 'store_id' => $val['store_id']])
//                        ->increment('count', $val['count'], ['sales_count' => DB::raw('sales_count - ' . $val['count']), 'total_netglod_weight' => DB::raw('total_netglod_weight + ' . $val['weight'])]);
                } else {

                    $stockData = [
                        'count' => $goods['count'] + $val['count'],
                        'sales_count' => $goods['sales_count'] - $val['count']
                    ];
                    // 非一码多货 总件重和总金重
                    $stockData['total_piece_weight'] = $goods['total_piece_weight'] + ($goods['piece_weight'] * $val['count']);
                    $stockData['total_netglod_weight'] = $goods['total_netglod_weight'] + ($goods['netglod_weight'] * $val['count']);
                    $val['total_piece_weight'] = $goods['piece_weight'] * $val['count'];
                    $val['total_netglod_weight'] = $goods['netglod_weight'] * $val['count'];

                }
                // $goods['count'] =$stockData['count'];
                // $goods['total_piece_weight'] =$stockData['total_piece_weight']??0;
                // $goods['total_netglod_weight'] =$stockData['total_netglod_weight']??0;
                //$stockData['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($goods,$goods['is_gram']);
                list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($goods, $val, $goods['is_gram']);
                $stockData['total_cost_fee'] = $total_cost_fee;
                $stockData['costglod_price'] = $costglod_price;
                $stockData['piececost_fee'] = $piececost_fee;

                GoodsStockList::query()
                    ->where(['cp_id' => $cp_id, 'id' => $val['goods_stock_id'], 'store_id' => $val['store_id'], 'is_del' => 1])
                    ->update($stockData);

                $goodsinfo = json_decode($val['goodsinfo'], true);
                $goodsinfo['weight'] = $val['weight'];
                $goodsinfo['total_cost_fee'] = $val['total_cost_fee'];;
                $goodsinfo['costglod_price'] = $costglod_price;
                $goodsinfo['piececost_fee'] = $piececost_fee;

                Goods::goodsLogSales($request, 0, intval($val['store_id']), $goodsinfo, intval($val['count']), 92, $info->order_sn);

            }
            foreach ($sendgoodslist as $val) {
                GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'id' => $val['send_goods_stock_id'], 'is_del' => 1])
                    ->increment('count', $val['count']);
                $send_goods_info = json_decode($val['send_goods_info'], true);
                GoodsSendgoodsLog::create(
                    [
                        'cp_id' => $cp_id,
                        'store_id' => $val['store_id'],
                        'target_store_id' => $val['store_id'],
                        'type' => 7,
                        'sn_code' => $info->order_sn,
                        'sendgoods_name' => $send_goods_info['sendgoods_name'],
                        'goods_sn_code' => $send_goods_info['goods_sn_code'],
                        'count' => $val['count'],
                        'pieceprice' => $send_goods_info['pieceprice'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '销售取消'
                    ]
                );
            }
            OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time(), 'audit_remark' => $audit_remark,'update_at'=>time()]);
            OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
            OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
            OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
            OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_at' => time()]);
//            if($info->coupon_id>0){//设置优惠券取消
//                WxappCouponCodeList::where(['id'=>$info->coupon_id])->update(['is_used'=>1,'used_at'=>0,'user_order_id'=>0]);
//            }

            if ($info->audit_status == 2) {

                //如果存在使用余额、积分转预存的金额，是否退款到账户余额
                //如果赠送积分，是否扣除积分，如积分已使用如何处理
                $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();
                if ($info->mem_id > 0 && $info->issendpoints == 2 && $info->order_points > 0) {

                    $order_points = array_sum(array_column($goodslist, 'order_points'));
                    if (($meminfo->points_current - $order_points) < 0) {
                        $order_points = $meminfo->points_current;
                    }

                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $info->mem_id,
                        'type' => 24,
                        'store_id' => $info->store_id,
                        'change_val' => $order_points,
                        'change_before' => $meminfo->points_current,
                        'change_after' => $meminfo->points_current - $order_points,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '订单撤审积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '订单撤审扣除积分',
                    ];
                    MemberPointsChangelog::create($data);
                    Member::where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total - ' . ($order_points)),
                        'points_current' => DB::raw('points_current - ' . ($order_points))
                    ]);
                }

                if ($info->mem_id > 0 && ($info->balance_money > 0 || $info->pointstobalance > 0)) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $info->mem_id,
                        'type' => 98,
                        'store_id' => $info->store_id,
                        'change_val' => $info->balance_money,
                        'change_before' => $meminfo->pre_money,
                        'change_after' => $meminfo->pre_money + $info->balance_money,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '订单撤审返回余额']),
                        'create_account_id' => $info->create_account_id,
                        'update_account_id' => $info->update_account_id,
                        'create_account_real_name' => $info->create_account_real_name,
                        'update_account_real_name' => $info->update_account_real_name,
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '订单撤审返回余额',
                    ];
                    MemberBalanceChangelog::create($data);
                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'pre_money' => DB::raw('pre_money + ' . $info->balance_money),
                        'pointstobalance' => DB::raw('pointstobalance + ' . $info->pointstobalance)
                    ]);
                }

                //扣除消费次数
                $member = Member::query()->where(['id' => $info->mem_id ?? 0, 'cp_id' => $cp_id, 'is_del' => 1])->first();
                if (!empty($member)) {
                    $member = $member->toArray();
                    $shopping_times = $member['shopping_times'] > 0 ? ($member['shopping_times'] - 1) : 0;
                    $avg_shopping_money = $shopping_times > 0 ? ($member['shopping_money_total'] / $shopping_times) : 0;
                    $shopping_money_total = $member['shopping_money_total'] - $info->real_money;
                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => $shopping_times,
                        'shopping_money_total' => $shopping_money_total,
                        'avg_shopping_money' => $avg_shopping_money,
                        'last_shopping_at' => $info->create_at
                    ]);

                }

                //核销优惠券 没办法回退

                //截金处理 && 旧料处理-旧料库
                Stock::where([
                    ['order_sncode', '=', $info->order_sn],
                    ['stock_status', '=', 1],
                ])->update([
                    'count' => 0,
                    'piece_weight' => 0,
                    'piece_weight_new' => 0,
                    'exchange_amount' => 0,
                    'stock_status' => 7, //旧料库存 撤单
                ]);
                //旧料处理-上柜
                foreach ($recoverygoodslist as $recoverygoods) {
                    if ($recoverygoods['change_type'] != 1) {
                        //上柜
                        $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                        if ($goodsStock) {
                            $goodsStock = $goodsStock->toArray();
                            //recovery_type =1按克，2标价
                            $count = $goodsStock['count'] - $recoverygoods['count'];
                            if ($recoverygoods['recovery_type'] == 1) {
                                if ($goodsStock['is_code_more'] == 2) {
                                    $log_total_netglod_weight = $recoverygoods['weight'];
                                    $log_total_piece_weight = 0;

                                    $total_piece_weight = 0;
                                    $total_netglod_weight = $goodsStock['total_netglod_weight'] - $recoverygoods['weight'];

                                } else {

                                    // 非一码多货
                                    $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                    $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                    $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                    $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                }
                            } else {
                                $total_piece_weight = $goodsStock['piece_weight'] * $count;
                                $total_netglod_weight = $goodsStock['netglod_weight'] * $count;

                                $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];

                            }
                            $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                            $recoverygoods['total_piece_weight'] = $log_total_piece_weight ?? 0;

                            $is_gram = GoodsCategory::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                                ->where('id', $goodsStock['goods_category_id'])
                                ->value('is_gram') ?? 0;

                            list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsStock, $recoverygoods);

                            $goodsStock['count'] = $count;
                            $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                            $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;

                            //  $total_cost_fee = (new Goods())->computeOriginalTotalCost($goodsStock, $is_gram);


                            $stockArr = [
                                'count' => $count,
                                'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                                'total_piece_weight' => $goodsStock['total_piece_weight'],
                                'total_cost_fee' => $remaining_cost_fee
                            ];

                            GoodsStockList::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])
                                ->update($stockArr);
                            $stockdata = $goodsStock;
                            $stockdata['count'] = $recoverygoods['count'];
                            $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                            $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                            $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;
                            Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 94, $info->order_sn);
                        }
                    }

                }


                //收支流水
                Financial::createMoneyLogByAuditCancel($cp_id, $info, $info->pay_money, -1);

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '订单撤销失败' . $e->getLine()]);

        }
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }


    public function doorderauditcancelmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $audit_remark = $request->audit_remark ?? '';
        if ($audit_remark == '') {
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info_more_arr = OrderSales::where([
            ['cp_id', '=', $cp_id],
            ['audit_status', '<', 3]
        ])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核或未支付订单']);
        }


        if ($accountinfo['type'] == 1 || $accountinfo['type'] == 2) {
            $info_more_count = OrderSales::where([
                ['cp_id', '=', $cp_id],
                ['audit_status', '=', 2]
            ])->whereIn('id', $ids)
                ->get();
            foreach ($info_more_count as $info2) {
                if (date('Y-m-d', $info2['create_at']) != date('Y-m-d')) {
                    return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
                }
            }
        }

//        if ($accountinfo['type']==9 ) {
//            $info_more_count = OrderSales::where([
//                ['cp_id', '=' ,$cp_id],
//                ['audit_status','<',3]
//            ])->whereIn('id', $ids)->count();
//            if($info_more_count!=count($ids)){
//                return response()->json(['code' => '001', 'msg' => '订单数据错误请刷新列表后重新选择']);
//            }
//        }


        // 获取所有订单编码的名字
        $order_sns = $info_more_arr->pluck('order_sn');
        //旧料表
        $oldmaterialcount = Stock::where([['order_sncode', 'in', $order_sns], ['cp_id', '=', $cp_id]])->get()->toArray();
        if (!empty($oldmaterialcount)) {
            foreach ($oldmaterialcount as $v) {
                if ($v['is_del'] == 2 || $v['stock_status'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单下的旧料不在库，不支持撤单']);
                }
            }
        }


        //旧料库存表
        $recoverygoodslist = OrderSalesRecoveryGoods::whereIn('pid', $ids)->where('is_del', 1)->get()->toArray();
        foreach ($recoverygoodslist as $recoverygoods) {
            if ($recoverygoods['change_type'] != 1) {
                //上柜
                $goodinfo = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $recoverygoods->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                    ->select(['total_netglod_weight', 'total_piece_weight', 'is_del'])
                    ->first()
                    ->toArray();
                if ($goodinfo['is_del'] != 1) {
                    return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                }
                $recoverygoodsweight = $recoverygoods['weight'] * $recoverygoods['count'];
                if ($recoverygoods['recovery_type'] == 1) {
                    //total_netglod_weight
                    if ($recoverygoodsweight > $goodinfo['total_netglod_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                } else {
                    //total_piece_weight
                    if ($recoverygoodsweight > $goodinfo['total_piece_weight']) {
                        return response()->json(['code' => '001', 'msg' => '该订单商品库存不足不支持撤单']);
                    }
                }
            }

        }


        DB::beginTransaction();
        try {

            foreach ($info_more_arr as $info) {
                $id = $info->id;

                $goodslist = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'red_status' => 1])->get()->toArray();

                if (empty($goodslist)) {
                    return response()->json(['code' => '001', 'msg' => '商品信息不存在或者存在红冲商品，不能撤单']);
                }

                $sendgoodslist = OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->get()->toArray();
                $goodsIds = array_column($goodslist, 'goods_stock_id');
                $goodsStock = (new GoodsStockList())->getGoodsStockByIds($cp_id, $goodsIds);
                foreach ($goodslist as $val) {
                    $goods = $goodsStock[$val['goods_stock_id']] ?? [];
                    if ($goods['is_code_more'] == 2) {
                        $stockData = [
                            'count' => $goods['count'] + $val['count'],
                            'sales_count' => $goods['sales_count'] - $val['count']
                        ];
                        $stockData['total_netglod_weight'] = $goods['total_netglod_weight'] + $val['weight'];
                        $val['total_netglod_weight'] = $val['weight'];

                    } else {

                        $stockData = [
                            'count' => $goods['count'] + $val['count'],
                            'sales_count' => $goods['sales_count'] - $val['count']
                        ];
                        // 非一码多货 总件重和总金重
                        $val['total_piece_weight'] = $goods['piece_weight'] * $val['count'];
                        $val['total_netglod_weight'] = $goods['netglod_weight'] * $val['count'];
                        $stockData['total_piece_weight'] = $goods['total_piece_weight'] + ($goods['piece_weight'] * $val['count']);
                        $stockData['total_netglod_weight'] = $goods['total_netglod_weight'] + ($goods['netglod_weight'] * $val['count']);
                    }
                    // $goods['count'] =$stockData['count'];
                    // $goods['total_piece_weight'] =$stockData['total_piece_weight']??0;
                    // $goods['total_netglod_weight'] =$stockData['total_netglod_weight']??0;
                    // $stockData['total_cost_fee'] = (new Goods())->computeOriginalTotalCost($goods,$goods['is_gram']);

                    list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($goods, $val, $goods['is_gram']);
                    $stockData['total_cost_fee'] = $total_cost_fee;
                    $stockData['costglod_price'] = $costglod_price;
                    $stockData['piececost_fee'] = $piececost_fee;

                    GoodsStockList::query()
                        ->where(['cp_id' => $cp_id, 'id' => $val['goods_stock_id'], 'store_id' => $val['store_id'], 'is_del' => 1])
                        ->update($stockData);

                    $goodsinfo = json_decode($val['goodsinfo'], true);
                    $goodsinfo['weight'] = $val['weight'];
                    $goodsinfo['total_cost_fee'] = $val['total_cost_fee'];;
                    $goodsinfo['costglod_price'] = $costglod_price;
                    $goodsinfo['piececost_fee'] = $piececost_fee;
                    Goods::goodsLogSales($request, 0, intval($val['store_id']), $goodsinfo, intval($val['count']), 92, $info->order_sn);

                }
                foreach ($sendgoodslist as $val) {
                    GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'id' => $val['send_goods_stock_id'], 'is_del' => 1])
                        ->increment('count', $val['count']);
                    $send_goods_info = json_decode($val['send_goods_info'], true);
                    GoodsSendgoodsLog::create(
                        [
                            'cp_id' => $cp_id,
                            'store_id' => $val['store_id'],
                            'target_store_id' => $val['store_id'],
                            'type' => 7,
                            'sn_code' => $info->order_sn,
                            'sendgoods_name' => $send_goods_info['sendgoods_name'],
                            'goods_sn_code' => $send_goods_info['goods_sn_code'],
                            'count' => $val['count'],
                            'pieceprice' => $send_goods_info['pieceprice'],
                            'create_at' => time(),
                            'update_at' => time(),
                            'remark' => '销售取消'
                        ]
                    );
                }
                OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time(), 'audit_remark' => $audit_remark,'update_at'=>time()]);
                OrderSalesGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
                OrderSalesRecoveryGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
                OrderSalesSendGoods::where(['pid' => $id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time()]);
                OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_at' => time()]);
                if ($info->coupon_id > 0) {//设置优惠券取消
                    WxappCouponCodeList::where(['id' => $info->coupon_id])->update(['is_used' => 1, 'used_at' => 0, 'user_order_id' => 0]);
                }

                if ($info->audit_status == 2) {

                    //如果存在使用余额、积分转预存的金额，是否退款到账户余额
                    //如果赠送积分，是否扣除积分，如积分已使用如何处理
                    $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();
                    if ($info->mem_id > 0 && $info->issendpoints == 2 && $info->order_points > 0) {

                        $order_points = array_sum(array_column($goodslist, 'order_points'));
                        if (($meminfo->points_current - $order_points) < 0) {
                            $order_points = $meminfo->points_current;
                        }

                        $data = [
                            'cp_id' => $cp_id,
                            'mem_id' => $info->mem_id,
                            'type' => 24,
                            'store_id' => $info->store_id,
                            'change_val' => $order_points,
                            'change_before' => $meminfo->points_current,
                            'change_after' => $meminfo->points_current - $order_points,
                            'sales_account_id' => $info->shopping_account_id1,
                            'loginfo' => json_encode(['title' => '订单撤审积分']),
                            'create_account_id' => $accountinfo['id'],
                            'update_account_id' => $accountinfo['id'],
                            'create_account_real_name' => $accountinfo['real_name'],
                            'update_account_real_name' => $accountinfo['real_name'],
                            'create_at' => time(),
                            'update_at' => time(),
                            'remark' => '订单撤审扣除积分',
                        ];
                        MemberPointsChangelog::create($data);
                        Member::where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                            // 'points_total' => DB::raw('points_total - ' . ($info)),
                            'points_current' => DB::raw('points_current - ' . ($order_points))
                        ]);
                    }

                    if ($info->mem_id > 0 && ($info->balance_money > 0 || $info->pointstobalance > 0)) {
                        $data = [
                            'cp_id' => $cp_id,
                            'mem_id' => $info->mem_id,
                            'type' => 98,
                            'store_id' => $info->store_id,
                            'change_val' => $info->balance_money,
                            'change_before' => $meminfo->pre_money,
                            'change_after' => $meminfo->pre_money + $info->balance_money,
                            'sales_account_id' => $info->shopping_account_id1,
                            'loginfo' => json_encode(['title' => '订单撤审返回余额']),
                            'create_account_id' => $info->create_account_id,
                            'update_account_id' => $info->update_account_id,
                            'create_account_real_name' => $info->create_account_real_name,
                            'update_account_real_name' => $info->update_account_real_name,
                            'create_at' => time(),
                            'update_at' => time(),
                            'remark' => '订单撤审返回余额',
                        ];
                        MemberBalanceChangelog::create($data);
                        Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                            'pre_money' => DB::raw('pre_money + ' . $info->balance_money),
                            'pointstobalance' => DB::raw('pointstobalance + ' . $info->pointstobalance)
                        ]);
                    }

                    $member = Member::query()->where(['id' => $info->mem_id ?? 0, 'cp_id' => $cp_id, 'is_del' => 1])->first();
                    if (!empty($member)) {
                        $member = $member->toArray();
                        $shopping_times = $member['shopping_times'] > 0 ? ($member['shopping_times'] - 1) : 0;
                        $avg_shopping_money = $shopping_times > 0 ? ($member['shopping_money_total'] / $shopping_times) : 0;
                        $shopping_money_total = $member['shopping_money_total'] - $info->total_money;
                        Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                            'shopping_times' => $shopping_times,
                            'shopping_money_total' => $shopping_money_total,
                            'avg_shopping_money' => $avg_shopping_money,
                            'last_shopping_at' => $info->create_at
                        ]);

                    }

                    //核销优惠券 没办法回退

                    //截金处理 && 旧料处理-旧料库
                    Stock::where([
                        ['order_sncode', '=', $info->order_sn],
                        ['stock_status', '=', 1],
                    ])
                        ->update([
                            'count' => 0,
                            'piece_weight' => 0,
                            'piece_weight_new' => 0,
                            'exchange_amount' => 0,
                            'stock_status' => 7,//旧料撤单
                        ]);
                    //旧料处理-上柜
                    foreach ($recoverygoodslist as $recoverygoods) {
                        if ($recoverygoods['change_type'] != 1) {
                            //上柜
                            $goodsStock = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code'], 'is_del' => 1])->first();
                            if ($goodsStock) {
                                $goodsStock = $goodsStock->toArray();
                                //recovery_type =1按克，2标价
                                $count = $goodsStock['count'] - $recoverygoods['count'];
                                if ($recoverygoods['recovery_type'] == 1) {
                                    if ($goodsStock['is_code_more'] == 2) {
                                        $log_total_netglod_weight = $recoverygoods['weight'];
                                        $log_total_piece_weight = 0;

                                        $total_netglod_weight = $goodsStock['total_netglod_weight'] - $recoverygoods['weight'];
                                        $total_piece_weight = 0;
                                    } else {
                                        // 非一码多货
                                        $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                        $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                        $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                        $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                    }
                                } else {
                                    $total_netglod_weight = $goodsStock['netglod_weight'] * $count;
                                    $total_piece_weight = $goodsStock['piece_weight'] * $count;

                                    $log_total_piece_weight = $goodsStock['piece_weight'] * $recoverygoods['count'];
                                    $log_total_netglod_weight = $goodsStock['netglod_weight'] * $recoverygoods['count'];
                                }
                                $recoverygoods['total_piece_weight'] = $log_total_piece_weight ?? 0;
                                $recoverygoods['total_netglod_weight'] = $log_total_netglod_weight ?? 0;

                                list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($goodsStock, $recoverygoods);

                                $is_gram = GoodsCategory::query()
                                    ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id])
                                    ->where('id', $goodsStock['goods_category_id'])
                                    ->value('is_gram') ?? 0;

                                $goodsStock['count'] = $count;
                                $goodsStock['total_netglod_weight'] = $total_netglod_weight ?? 0;
                                $goodsStock['total_piece_weight'] = $total_piece_weight ?? 0;

                                //$total_cost_fee = (new Goods())->computeOriginalTotalCost($goodsStock, $is_gram);
                                $stockArr = [
                                    'count' => $count,
                                    'total_netglod_weight' => $goodsStock['total_netglod_weight'],
                                    'total_piece_weight' => $goodsStock['total_piece_weight'],
                                    'total_cost_fee' => $remaining_cost_fee
                                ];
                                GoodsStockList::query()
                                    ->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $recoverygoods['goods_sn_code']])
                                    ->update($stockArr);
                                $stockdata = $goodsStock;
                                $stockdata['count'] = $recoverygoods['count'];
                                $stockdata['total_cost_fee'] = $recoverygoods['total_cost_fee'] ?? 0;
                                $stockdata['total_netglod_weight'] = $log_total_netglod_weight ?? 0;
                                $stockdata['total_piece_weight'] = $log_total_piece_weight ?? 0;
                                Goods::goodsLog($request, 0, intval($stockdata['store_id']), $stockdata, intval($stockdata['count']), 94, $info->order_sn);
                            }
                        }

                    }

                    //收支流水
                    Financial::createMoneyLogByAuditCancel($cp_id, $info, $info->pay_money, -1);

                }
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '订单取消失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }

    /**
     * 红冲
     */
    public function doredflush(Request $request)
    {
        $id = $request->id ?? 0;
        $gids = $request->gids;

        $gids = is_array($gids) ? $gids : (is_array(json_decode($gids, true)) ? json_decode($gids, true) : []);

        if (count($gids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择要红冲的订单商品']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '该订单未审核成功']);
        }

        $recoverygoodslist = OrderSalesRecoveryGoods::query()->where(['pid' => $id, 'is_del' => 1])->get()->toArray();
        if (count($recoverygoodslist) > 0) {
            return response()->json(['code' => '001', 'msg' => '包含旧料信息的订单无法红冲']);
        }


        if (date('Y-m') == date('Y-m', $info->order_at) || date('Ym') < date('Ym', $info->order_at)) {
            return response()->json(['code' => '001', 'msg' => '非当月订单无法红冲']);
        }

        $goodslist = OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'red_status' => 1])->whereIn('id', $gids)->get()->toArray();

        if (count($goodslist) != count($gids)) {
            return response()->json(['code' => '001', 'msg' => '请选择正确的红冲订单商品']);
        }


        $maindata = [
            'order_id' => $id,
            'gids' => join(',', $gids),
            'cp_id' => $info->cp_id,
            'store_id' => $info->store_id,
            'mem_id' => $info->mem_id,
            'classesset_id' => $info->classesset_id,
            'order_sn' => $info->order_sn,
            'shopping_account_id1' => $info->shopping_account_id1,
            'shopping_account_id2' => $info->shopping_account_id2,
            //$sub_real_total_moeny=array_sum(array_column($goodslist_new, 'real_total_money'));
            'coupon_money' => array_sum(array_column($goodslist, 'sub_coupon_money')),
            'total_money' => array_sum(array_column($goodslist, 'total_money')),
            'real_money' => array_sum(array_column($goodslist, 'real_total_money')),

            'goods_total_money' => array_sum(array_column($goodslist, 'total_money')),
            'goods_real_money' => array_sum(array_column($goodslist, 'real_total_money_without_mian')),
            'changegoods_money' => array_sum(array_column($goodslist, 'sub_recovery_goods_meony')),
            'dold_fee_total' => array_sum(array_column($goodslist, 'dold_fee_total')),
            'order_points' => array_sum(array_column($goodslist, 'order_points')),

            'add_fee' => array_sum(array_column($goodslist, 'add_fee1')) + array_sum(array_column($goodslist, 'add_fee2')),
            'truncate_glod_weight' => array_sum(array_column($goodslist, 'truncate_glod_weight')),
            'truncate_glod_money' => array_sum(array_column($goodslist, 'truncate_glod_money')),
            'order_discount' => $info->order_discount,

            'order_at' => $info->order_at,
        ];
        $maindata['create_account_id'] = $accountinfo['id'];
        $maindata['update_account_id'] = $accountinfo['id'];
        $maindata['create_account_real_name'] = $accountinfo['real_name'];
        $maindata['update_account_real_name'] = $accountinfo['real_name'];
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        //红冲订单汇总数据

        //更改子订单状态
        OrderSalesGoods::where(['pid' => $id, 'is_del' => 1, 'red_status' => 1])->whereIn('id', $gids)->update(['red_status' => 2, 'red_at' => time()]);
        // 修改红冲记录
        OrderCommissionLog::where(['pid' => $id, 'cp_id' => $cp_id, 'red_status' => 1])->whereIn('sub_id', $gids)->update(['red_status' => 2, 'red_at' => time()]);
        //红冲主订单
        OrderSalesRedflush::create($maindata);
        return response()->json(['code' => '000', 'msg' => '订单红冲成功']);

    }

    /**
     * 更改订单信息
     */
    public function changeorderinfo(Request $request)
    {
        //赠品、班次、导购信息，支付方式、下单日期、备注、生日
        $req_data = $request->only([
            'id', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'sendgoodslist', 'mixed_payment',
            'order_at', 'remark', 'lunar_bdate', 'solar_bdate'
        ]);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        $info = OrderSales::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $current_store_id = $info->store_id;
        //赠品
        $sendgoodslist = is_array($req_data['sendgoodslist']) ? $req_data['sendgoodslist'] : (is_array(json_decode($req_data['sendgoodslist'], true)) ? json_decode($req_data['sendgoodslist'], true) : []);
        //校验赠品信息
        $sendgoodslist_new = [];
        $ValidateGoods = new ValidateOrderOrderSales('checksendgoods');
        foreach ($sendgoodslist as $sendgoods) {
            if (!$ValidateGoods->check($sendgoods)) {
                return response()->json(['code' => '001', 'msg' => $ValidateGoods->getError()]);
            }
            $sendgoodsinfo = GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'id' => $sendgoods['send_goods_stock_id'], 'is_del' => 1])->first();
            if (!$sendgoodsinfo) {
                return response()->json(['code' => '001', 'msg' => '无效赠品信息']);
            }
            $sendgoodsinfo = $sendgoodsinfo->toArray();

            if ($sendgoodsinfo['count'] < $sendgoods['count']) {
                return response()->json(['code' => '001', 'msg' => '库存不足']);
            }
            $item = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'send_goods_stock_id' => $sendgoods['send_goods_stock_id'],
                'count' => $sendgoods['count'],
                'send_goods_info' => json_encode($sendgoodsinfo),
                'sendgoods_name' => $sendgoodsinfo['sendgoods_name'],
                'goods_sn_code' => $sendgoodsinfo['goods_sn_code'],
                'pieceprice' => $sendgoodsinfo['pieceprice'],
                'pid' => $req_data['id'],
                'mem_id' => $info->mem_id
            ];
            $sendgoodslist_new[] = $item;
        }
        $maindata = [];
        $maindata['shopping_account_id1'] = isset($req_data['shopping_account_id1']) ? $req_data['shopping_account_id1'] : 0;
        $maindata['shopping_account_id2'] = isset($req_data['shopping_account_id2']) ? $req_data['shopping_account_id2'] : 0;
        $maindata['classesset_id'] = isset($req_data['classesset_id']) ? intval($req_data['classesset_id']) : 0;
        $maindata['pay_type_id'] = isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0;
        $maindata['mixed_payment'] = (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']);
        $maindata['pay_type_name'] = empty($req_data['pay_type_id']) ? '' : ($req_data['pay_type_id'] == -1 ? '混合支付' : PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name'));
        $maindata['order_at'] = isset($req_data['order_at']) ? strtotime($req_data['order_at']) : time();
        $maindata['remark'] = isset($req_data['remark']) ? $req_data['remark'] : '';
        $maindata['update_at'] =  time();
        $memdata = [
            'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
            'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
            'update_at' => time()
        ];

        $sendgoodslist = OrderSalesSendGoods::where(['pid' => $req_data['id'], 'is_del' => 1])->get()->toArray();


        DB::beginTransaction();
        try {
            foreach ($sendgoodslist as $val) {
                GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'id' => $val['send_goods_stock_id'], 'is_del' => 1])
                    ->increment('count', $val['count']);
                $send_goods_info = json_decode($val['send_goods_info'], true);
                GoodsSendgoodsLog::create(
                    [
                        'cp_id' => $cp_id,
                        'store_id' => $val['store_id'],
                        'target_store_id' => $val['store_id'],
                        'type' => 7,
                        'sn_code' => $info->order_sn,
                        'sendgoods_name' => $send_goods_info['sendgoods_name'],
                        'goods_sn_code' => $send_goods_info['goods_sn_code'],
                        'count' => $val['count'],
                        'pieceprice' => $send_goods_info['pieceprice'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '销售编辑赠品'
                    ]
                );
            }
            OrderSales::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->update($maindata);

            $salesgoods = [];
            $salesgoods['shopping_account_id1'] = $maindata['shopping_account_id1'];
            $salesgoods['shopping_account_id2'] = $maindata['shopping_account_id2'];
            $salesgoods['classesset_id'] = $maindata['classesset_id'];
            $salesgoods['pay_type_id'] = $maindata['pay_type_id'];
            //$salesgoods['mixed_payment'] = $maindata['mixed_payment'];
            //$salesgoods['pay_type_name'] = $maindata['pay_type_name'];
            $salesgoods['order_at'] = $maindata['order_at'];

            OrderSalesGoods::query()
                ->where(['pid' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                ->update($salesgoods);

            // 如果有换货则需要更新下单时间
            $recovery = OrderSalesRecoveryGoods::query()
                ->where(['pid' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                ->first();
            if (!empty($recovery)) {
                $recoveryData = [];
                $recoveryData['shopping_account_id1'] = $maindata['shopping_account_id1'];
                $recoveryData['shopping_account_id2'] = $maindata['shopping_account_id2'];
                $recoveryData['classesset_id'] = $maindata['classesset_id'];
                $recoveryData['order_at'] = $maindata['order_at'];
                OrderSalesRecoveryGoods::query()
                    ->where(['pid' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update($recoveryData);
            }

            $info->mem_id > 0 && Member::query()->where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update($memdata);
            foreach ($sendgoodslist_new as $sgval) {
                //更新库存相关
                //下单减少库存，如审核取消则库存退还，如修改订单则更改库存
                GoodsSendgoodsStock::where(['cp_id' => $cp_id, 'store_id' => $current_store_id, 'id' => $sendgoods['send_goods_stock_id'], 'is_del' => 1])
                    ->decrement('count', $sgval['count']);
                $send_goods_info = json_decode($sgval['send_goods_info'], true);
                GoodsSendgoodsLog::create(
                    [
                        'cp_id' => $cp_id,
                        'store_id' => $current_store_id,
                        'target_store_id' => $current_store_id,
                        'type' => 2,
                        'sn_code' => $info->order_sn,
                        'sendgoods_name' => $send_goods_info['sendgoods_name'],
                        'goods_sn_code' => $send_goods_info['goods_sn_code'],
                        'count' => $sgval['count'],
                        'pieceprice' => $send_goods_info['pieceprice'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '销售赠送'
                    ]
                );
            }

            OrderSalesSendGoods::where(['pid' => $req_data['id'], 'is_del' => 1])->update(['is_del' => 2, 'del_at' => time()]);
            count($sendgoodslist_new) > 0 && OrderSalesSendGoods::query()->insert($sendgoodslist_new);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '订单修改失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '订单修改成功']);


    }

    /**
     * 更改会员信息
     */
    public function changememinfo(Request $request)
    {
        $req_data = $request->only(['id', 'mobile', 'mem_card_no', 'real_name', 'lunar_bdate', 'solar_bdate']);
        $Validate = new ValidateOrderOrderSales('checkmember');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $id = $req_data['id'];
        $info = OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->balance_money > 0 || $info->pointstobalance > 0) {
            return response()->json(['code' => '001', 'msg' => '订单使用预存金额或积分金额，无法更改']);
        }

        $meminfo = Member::query()->where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

        if ($info->mem_id > 0) {
            $old_mem_id = $info->mem_id;
            if (!empty($meminfo)) {
                Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id, 'is_del' => 1])->update([
                    'mobile' => isset($req_data['mobile']) ? $req_data['mobile'] : '',
                    'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                    'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                    'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                    'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                ]);
                OrderSales::query()->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update(['mem_id' => $meminfo->id]);
                OrderSalesGoods::query()->where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update(['mem_id' => $meminfo->id]);
                OrderSalesRecoveryGoods::query()->where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update(['mem_id' => $meminfo->id]);
                OrderSalesSendGoods::query()->where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update(['mem_id' => $meminfo->id]);
                $new_mem_id = $meminfo->id;
            } else {
                $data = [
                    'create_at' => time(),
                    'update_at' => time(),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                ];
                $data['cp_id'] = $cp_id;
                $data['store_id'] = $info->store_id;

                $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';

                $ins_mem_id = Member::create($data)->id;
                CommonMember::setMemInitPoints($request, $ins_mem_id);
                OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                OrderSalesGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                OrderSalesRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                OrderSalesSendGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                $new_mem_id = $ins_mem_id;
            }
            //会员升级
            if ($new_mem_id > 0) {
                CommonMember::checkMemLv($new_mem_id);
            }

            if ($info->audit_status == 2 && $new_mem_id != $old_mem_id) {
                //信息变更--积分扣除
                //老积分扣除，新积分加上
                $new_mem_info = Member::query()->where(['cp_id' => $cp_id, 'id' => $new_mem_id, 'is_del' => 1])->first();
                $old_mem_info = Member::query()->where(['cp_id' => $cp_id, 'id' => $old_mem_id])->first();
                if ($info->issendpoints == 2 && ($info->order_points > 0 || $info->order_points_recovery > 0)) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $new_mem_id,
                        'type' => 3,
                        'store_id' => $info->store_id,
                        'change_val' => ($info->order_points_recovery + $info->order_points),
                        'change_before' => $new_mem_info->points_current,
                        'change_after' => $new_mem_info->points_current + ($info->order_points_recovery + $info->order_points),
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '购物赠送积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '购物赠送积分',
                    ];
                    MemberPointsChangelog::create($data);
                    Member::where(['id' => $new_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total + ' . ($info->order_points_recovery + $info->order_points)),
                        'points_current' => DB::raw('points_current + ' . ($info->order_points_recovery + $info->order_points)),
                        'shopping_times' => DB::raw('shopping_times + 1 ')
                    ]);
                    CommonMember::checkMemLv($new_mem_info->id);//会员升级
                } else {
                    Member::where(['id' => $new_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => DB::raw('shopping_times + 1 ')
                    ]);
                }

                if ($info->issendpoints == 2 && ($info->order_points > 0 || $info->order_points_recovery > 0)) {
                    $change_val = ($info->order_points_recovery + $info->order_points);
                    if ($change_val > $old_mem_info->points_current) {
                        $change_val = $old_mem_info->points_current;
                    }

                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $old_mem_id,
                        'type' => 24,
                        'store_id' => $info->store_id,
                        'change_val' => -$change_val,
                        'change_before' => $old_mem_info->points_current,
                        'change_after' => $old_mem_info->points_current - $change_val,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '信息变更,扣除积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '信息变更，扣除积分',
                    ];
                    MemberPointsChangelog::create($data);

                    Member::where(['id' => $old_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total - ' . $change_val),
                        'points_current' => DB::raw('points_current - ' . $change_val),
                        'shopping_times' => DB::raw('shopping_times - 1 ')
                    ]);
                    CommonMember::checkMemLv($old_mem_info->id);//会员升级
                } else {
                    Member::where(['id' => $old_mem_info->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'shopping_times' => DB::raw('shopping_times - 1 ')
                    ]);
                }


            }


            return response()->json(['code' => '000', 'msg' => '会员信息变更成功']);
        } else {
            DB::beginTransaction();
            try {
                if ($meminfo) {
                    if ($info->audit_status == 2) {
                        Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id])->update([
                            'mobile' => isset($req_data['mobile']) ? $req_data['mobile'] : '',
                            'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                            'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                            'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                            'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                            'shopping_times' => DB::raw('shopping_times + 1 ')
                        ]);
                    } else {
                        Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id])->update([
                            'mobile' => isset($req_data['mobile']) ? $req_data['mobile'] : '',
                            'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                            'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                            'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                            'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                        ]);
                    }


                    OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    OrderSalesGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    OrderSalesRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                    OrderSalesSendGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $meminfo->id]);
                } else {
                    $data = [
                        'create_at' => time(),
                        'update_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                    ];
                    $data['cp_id'] = $cp_id;
                    $data['store_id'] = $info->store_id;

                    $data['mobile'] = isset($req_data['mobile']) ? $req_data['mobile'] : '';
                    $data['mem_card_no'] = isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '';
                    $data['real_name'] = isset($req_data['real_name']) ? $req_data['real_name'] : '';
                    $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '';
                    $data['solar_bdate'] = isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '';
                    if ($info->audit_status == 2) {
                        $data['shopping_times'] = 1;
                    }
                    $ins_mem_id = Member::create($data)->id;
                    CommonMember::setMemInitPoints($request, $ins_mem_id);
                    OrderSales::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                    OrderSalesGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                    OrderSalesRecoveryGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                    OrderSalesSendGoods::where(['pid' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id' => $ins_mem_id]);
                }

                $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'], 'is_del' => 1])->first();

                if ($meminfo->id > 0 && $info->issendpoints == 2 && $info->audit_status == 2 && ($info->order_points > 0 || $info->order_points_recovery > 0)) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $meminfo->id,
                        'type' => 3,
                        'store_id' => $info->store_id,
                        'change_val' => ($info->order_points_recovery + $info->order_points),
                        'change_before' => $meminfo->points_current,
                        'change_after' => $meminfo->points_current + ($info->order_points_recovery + $info->order_points),
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '购物赠送积分']),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => '购物赠送积分',
                    ];
                    MemberPointsChangelog::create($data);

                    Member::where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => DB::raw('points_total + ' . ($info->order_points_recovery + $info->order_points)),
                        'points_current' => DB::raw('points_current + ' . ($info->order_points_recovery + $info->order_points))
                    ]);
                    CommonMember::checkMemLv($meminfo->id);//会员升级
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '会员信息绑定失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '会员信息绑定成功']);
        }


    }


    /**
     * 导出订单
     */
    public function doexport(Request $request)
    {
        $list = OrderSales::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['table_header' => '商品订单列表'],
            [
                'order_sn' => '订单号',
                'order_at' => '下单时间',
                'pay_status' => '支付状态',
                'shopping_account_info1' => '导购',
                'shopping_account_info2' => '副导购',
                'audit_status' => '审核状态',
                // 'goods_total_money' => '商品应收',
                'dold_fee_total' => '折旧费',
                'changegoods_money' => '换货金额',
                'add_fee' => '附加费',
                'truncate_glod_weight' => '截金重量',
                'truncate_glod_money' => '截金金额',
                'coupon_money' => '抵用券金额',
                'total_money' => '订单应收',
                'order_total_discount_moeny' => '优惠金额',
                'real_money' => '订单实收',
                'performance' => '业绩',
                'total_grossprofits' => '毛利',
                'order_discount' => '总折扣',
                'order_points' => '积分',
                'real_name' => '会员名称',
                'mobile' => '会员电话',
                'remark' => '备注',
                'create_account_real_name' => '创建人',
                'create_at' => '创建时间',
                'update_account_real_name' => '更新人',
                'update_at' => '更新时间',


            ]
        ];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['total_grossprofits']);
        }
        //'order_total_discount_moeny'=>$val['order_total_discount_moeny']/100, 订单总优惠金额(discount_moeny)
        foreach ($list as $val) {
            //计算订单业绩
            $total_performance = 0;
            if (!empty($val['goodslist'])) {
                foreach ($val['goodslist'] as $goods) {
                    if (isset($goods['performance'])) {
                        $total_performance += $goods['performance'];
                    }
                }
            }
            $exceldata[] = [
                'order_sn' => $val['order_sn'],
                'order_at' => date('Y-m-d', $val['order_at']),
                'pay_status' => $val['is_maker'] == 2 ? '未支付' : '已支付',
                'shopping_account_info1' => $val['shoppingaccountinfo1']['real_name'],
                'shopping_account_info2' => $val['shoppingaccountinfo2'] ? $val['shoppingaccountinfo2']['real_name'] : '',
                'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核' : '取消'),
                //'goods_total_money' => $val['goods_total_money'] / 100,
                'dold_fee_total' => $val['dold_fee_total'] / 100,
                'changegoods_money' => $val['changegoods_money'] / 100,
                'coupon_money' => $val['coupon_money'] / 100,
                'total_money' => $val['total_money'] / 100,
                'order_total_discount_moeny' => $val['discount_moeny'] / 100,
                'real_money' => $val['real_money'] / 100,
                'total_grossprofits' => array_sum(array_column($val['goodslist'], 'grossprofits')) / 100,

                'order_discount' => $val['order_discount'] > 0 ? $val['order_discount'] : '无折扣',
                'order_points' => $val['order_points'] + $val['order_points_recovery'],
                'real_name' => $val['memberinfo'] ? $val['memberinfo']['real_name'] : '',
                'mobile' => $val['memberinfo'] ? $val['memberinfo']['mobile'] : '',
                'remark' => $val['remark'],
                'create_account_real_name' => $val['create_account_real_name'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'add_fee' => $val['add_fee_total'] / 100,
                'truncate_glod_weight' => $val['truncate_glod_weight'],
                'truncate_glod_money' => $val['truncate_glod_money'] / 100,
                'performance' => $total_performance / 100,
            ];
        }
        //dd($exceldata);
        $filename = '订单导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 获取优惠券列表
     */

    public function getcanusecoupon(Request $request)
    {
        $mobile = $request->mobile;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];

        if (is_array($store_ids) || $store_ids == '' || $store_ids <= 0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        } else {
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }


        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $mobile, 'is_del' => 1])->first();
        if (!$meminfo) {
            return response()->json(['code' => '001', 'msg' => '会员不存在']);
        }
        $list = WxappCouponCodeList::where(['cp_id' => $cp_id, 'mem_id' => $meminfo->id, 'is_used' => 1, 'is_receive' => 2])->where('available_end_time', '>=', time())
            ->where(function ($q) use ($current_store_id) {
                $q->where('store_ids', '')->orWhereRaw('FIND_IN_SET(?,store_ids)', [$current_store_id]);;
            })
            ->get()->toArray();

        foreach ($list as &$val) {
            $val['stock_name'] = WxappCoupon::where(['id' => $val['coupon_id']])->value('stock_name');
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => $list]]);
    }


    /**
     *
     * 重算毛利：
     * 按克和一码多货的商品成本：编辑后的或补货后的成本金价*销售重量
     * 按件的商品成本：编辑后或补货后的单件成本*销售件数
     * 商品毛利=商品实收金额+旧料估值-编辑后或补货后的商品成本
     * 订单毛利=商品实收金额的和+旧料估值的和-编辑后或补货后商品成本的和
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rerungrossprofits(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $list = OrderSales::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->get()->toArray();
        if (count($list) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $infolist = OrderSalesGoods::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('pid', $ids)->get()->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $goodsinfo = GoodsStockList::where(['cp_id' => $cp_id, 'id' => $info['goods_stock_id'], 'store_id' => $info['store_id'], 'is_del' => 1])->first();

                if (empty($goodsinfo)) {
                    return response()->json(['code' => '001', 'msg' => '库存商品不存在无法计算毛利']);
                }

                $goodsinfo = $goodsinfo->toArray();

                /**
                 * 重算毛利：
                 * 按克和一码多货的商品成本：编辑后的或补货后的成本金价*销售重量
                 * 按件的商品成本：编辑后或补货后的单件成本*销售件数
                 * 商品毛利=商品实收金额+旧料估值-编辑后或补货后的商品成本
                 * 订单毛利=商品实收金额的和+旧料估值的和-编辑后或补货后商品成本的和
                 * 旧料估值=返厂金价（取最新的）*回收重量
                 **/

                if ($info['is_gram'] == 1) {
//                    $lastprice = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $info['store_id'], 'goods_category_id' => $info['goods_category_id'], 'is_del' => 1])
//                        ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();
//                    if (!$lastprice) {
//                        continue;
//                    }
//                    $price = $lastprice->sales_price;
//
//                    $money_sub = intval(($price - $info['price']) * $info['weight']);
//                    $cost_fee_new = intval($info['weight'] * ($goodsinfo['costglod_price'] + $goodsinfo['costgram_fee'])) + intval($info['count'] * $goodsinfo['costpiece_fee']);
//                    $cost_fee_sub = $cost_fee_new - $info['cost_fee'];
//                    $grossprofits = $info['grossprofits_old'] + $money_sub - $cost_fee_sub;
                    // 按克和一码多货的商品成本：编辑后的或补货后的成本金价*销售重量

                    $cost_fee_sub = $goodsinfo['costglod_price'] * $info['weight'];

                    //  OrderSalesGoods::where(['id' => $info['id']])->update(['grossprofits' => $grossprofits]);
                } else {
                    $cost_fee_sub = $goodsinfo['piececost_fee'] * $info['count'];
//                    $cost_fee_sub = $cost_fee_new - $info['cost_fee'];
//
//                    $money_sub = intval(($goodsinfo['label_price'] - $info['price']) * $info['count']);
//
//                    if ($info['discount'] > 0 && $info['discount'] < 100) {
//                        $money_sub = intval($money_sub * $info['discount'] / 100);
//                    }
//                    $grossprofits = $info['grossprofits_old'] + $money_sub - $cost_fee_sub;
//                    OrderSalesGoods::where(['id' => $info['id']])->update(['grossprofits' => $grossprofits]);
                }


                // 商品毛利=商品实收金额+旧料估值-编辑后或补货后的商品成本
                $grossprofits = $info['real_total_money'] + $info['sub_valuations'] - $cost_fee_sub;
                OrderSalesGoods::where(['id' => $info['id']])->update(['grossprofits' => $grossprofits]);

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '计算失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '计算成功']);
    }

    public function getorderprintdata(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        if ($id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data = ServicesOrderOrderSales::getOrderPrintData($id, $request);

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }


}
